locked
How to change the background of a button defined in Data template? RRS feed

  • Question

  • I am creating buttons dynamically. I have defined Button in data template. As per the dynamic count, number of buttons will be created. Whenever a button is clicked, I want an image background set to it. and when the other button is clicked, it should be reset back to original style. How can I do it? 

    And also tell me how to change the color of an image dynamically.

    Thanks :)

    Monday, October 7, 2013 10:11 AM

Answers

  • Hi,Prateeksha

    You can create two button style like image background style and original style  in xaml, when you click a button you can set the button style to image background style  in click event and then get the other button and set their style to original style.There are some codes you can refer to:

    In XAML:

     <Page.Resources>
            <Style x:Key="Buttonstyle" TargetType="Button">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="Assets/Logo.png"></ImageBrush>
                    </Setter.Value>
                </Setter>
            </Style>
            <Style x:Key="Buttonstyle2" TargetType="Button">
                <Setter Property="Background" Value="Transparent"/>
            </Style>
        </Page.Resources>
    
        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <ListView ItemsSource="{Binding}" x:Name="listview" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Content}" Click="Button_Click_1" x:Name="button"></Button>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>

    Code-Behind:

    public sealed partial class ButtonstyleChange : Page
        {
            public ButtonstyleChange()
            {
                this.InitializeComponent();
                ObservableCollection<ButtonContent> buttoncontent = new ObservableCollection<ButtonContent>();
                buttoncontent.Add(new ButtonContent { Content = "click" });
                buttoncontent.Add(new ButtonContent { Content = "click" });
                buttoncontent.Add(new ButtonContent { Content = "click" });
                listview.DataContext = buttoncontent;
    
            }
    
            /// <summary>
            /// Invoked when this page is about to be displayed in a Frame.
            /// </summary>
            /// <param name="e">Event data that describes how this page was reached.  The Parameter
            /// property is typically used to configure the page.</param>
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                var Buttonsource = sender as Button;
                var mystyle = this.Resources["Buttonstyle"] as Style;
                Buttonsource.Style = mystyle;
                for (int i = 0; i < listview.Items.Count; i++)
                {
                    var listviewitem = listview.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
                    var button = FindChild<Button>(listviewitem, "button");
                    if (button != Buttonsource)
                    {
    
                        button.Style = this.Resources["Buttonstyle2"] as Style;
                    }
                    
    
                }
            }
    
           //The method can find Button control in ListView DataTemplate
            public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
            {
                if (parent == null) return null;
                T foundChild = null;
                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    
                for (int i = 0; i < childrenCount; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    T childType = child as T;
    
                    if (childType == null)
                    {
                        foundChild = FindChild<T>(child, childName);
                        if (foundChild != null) break;
                    }
                    else if (!string.IsNullOrEmpty(childName))
                    {
                        var frameworkElement = child as FrameworkElement;
                        if (frameworkElement != null && frameworkElement.Name == childName)
                        {
                            foundChild = (T)child;
                            break;
                        }
    
                        foundChild = FindChild<T>(child, childName);
                        if (foundChild != null) break;
                    }
                    else
                    {
                        foundChild = (T)child;
                        break;
                    }
                }
    
                return foundChild;
            }
        }
        public class ButtonContent
        {
            public string Content { get; set; }
        }
    Best Wishes!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey. Thanks<br/> MSDN Community Support<br/> <br/> Please remember to &quot;Mark as Answer&quot; the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    • Marked as answer by Anne Jing Tuesday, October 15, 2013 8:13 AM
    Tuesday, October 8, 2013 5:36 AM

All replies

  • set class like this 

    ObservableCollection<MyClass> ButtonContent1 =new ObservableCollection<MyClass>();
    
    ButtonContent1.Add(new MyClass{Text="Text1",Color = "Red"});
    or #FF235647 use for
     and i = 0 to increment value
    
    ButtonContent1.Add(new MyClass{Text="Text2",Color = "Blue"});
    
    ButtonContent1.Add(new MyClass{Text="Text3",Color = "Green"});


    then

    <DataTemplate>
             <Button Width="150" Content="{Binding Text}"Background = "{Binding Color}" />
                                </DataTemplate>


    even create 3 styles in blend for a button

    then randomly set style= "{Binding style1}" too



    • Edited by prasanas Monday, October 7, 2013 12:15 PM
    Monday, October 7, 2013 12:12 PM
  • Hi,Prateeksha

    You can create two button style like image background style and original style  in xaml, when you click a button you can set the button style to image background style  in click event and then get the other button and set their style to original style.There are some codes you can refer to:

    In XAML:

     <Page.Resources>
            <Style x:Key="Buttonstyle" TargetType="Button">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="Assets/Logo.png"></ImageBrush>
                    </Setter.Value>
                </Setter>
            </Style>
            <Style x:Key="Buttonstyle2" TargetType="Button">
                <Setter Property="Background" Value="Transparent"/>
            </Style>
        </Page.Resources>
    
        <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
            <ListView ItemsSource="{Binding}" x:Name="listview" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Content}" Click="Button_Click_1" x:Name="button"></Button>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>

    Code-Behind:

    public sealed partial class ButtonstyleChange : Page
        {
            public ButtonstyleChange()
            {
                this.InitializeComponent();
                ObservableCollection<ButtonContent> buttoncontent = new ObservableCollection<ButtonContent>();
                buttoncontent.Add(new ButtonContent { Content = "click" });
                buttoncontent.Add(new ButtonContent { Content = "click" });
                buttoncontent.Add(new ButtonContent { Content = "click" });
                listview.DataContext = buttoncontent;
    
            }
    
            /// <summary>
            /// Invoked when this page is about to be displayed in a Frame.
            /// </summary>
            /// <param name="e">Event data that describes how this page was reached.  The Parameter
            /// property is typically used to configure the page.</param>
            protected override void OnNavigatedTo(NavigationEventArgs e)
            {
            }
    
            private void Button_Click_1(object sender, RoutedEventArgs e)
            {
                var Buttonsource = sender as Button;
                var mystyle = this.Resources["Buttonstyle"] as Style;
                Buttonsource.Style = mystyle;
                for (int i = 0; i < listview.Items.Count; i++)
                {
                    var listviewitem = listview.ItemContainerGenerator.ContainerFromIndex(i) as ListViewItem;
                    var button = FindChild<Button>(listviewitem, "button");
                    if (button != Buttonsource)
                    {
    
                        button.Style = this.Resources["Buttonstyle2"] as Style;
                    }
                    
    
                }
            }
    
           //The method can find Button control in ListView DataTemplate
            public static T FindChild<T>(DependencyObject parent, string childName) where T : DependencyObject
            {
                if (parent == null) return null;
                T foundChild = null;
                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    
                for (int i = 0; i < childrenCount; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    T childType = child as T;
    
                    if (childType == null)
                    {
                        foundChild = FindChild<T>(child, childName);
                        if (foundChild != null) break;
                    }
                    else if (!string.IsNullOrEmpty(childName))
                    {
                        var frameworkElement = child as FrameworkElement;
                        if (frameworkElement != null && frameworkElement.Name == childName)
                        {
                            foundChild = (T)child;
                            break;
                        }
    
                        foundChild = FindChild<T>(child, childName);
                        if (foundChild != null) break;
                    }
                    else
                    {
                        foundChild = (T)child;
                        break;
                    }
                }
    
                return foundChild;
            }
        }
        public class ButtonContent
        {
            public string Content { get; set; }
        }
    Best Wishes!


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey. Thanks<br/> MSDN Community Support<br/> <br/> Please remember to &quot;Mark as Answer&quot; the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    • Marked as answer by Anne Jing Tuesday, October 15, 2013 8:13 AM
    Tuesday, October 8, 2013 5:36 AM