none
Binding status of button RRS feed

  • Question

  • Hello,

    Trying to change image on button when button status is changed usying XAML binding, unfortunately I'm failed.

    Not sure what's wrong with the code. 

    XAML

        <Grid>
            <Button Height="36" HorizontalAlignment="Left" Margin="60,62,0,0" Name="button1" VerticalAlignment="Top" Width="37" MouseDown="button1_MouseDown">
                <StackPanel>                
                   <Image>
                        <Image.Style>
                            <Style TargetType="{x:Type Image}">
                                <Setter Property="Source" Value="D:\Pictures\trn_of.png"/>
                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding status}" Value="True">
                                        <Setter Property="Source" Value="D:\Pictures\trn_of.png" />
                                    </DataTrigger>
                                    <DataTrigger Binding="{Binding status}" Value="False">
                                        <Setter Property="Source" Value="D:\Pictures\trn_on.png" />
                                    </DataTrigger>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Source" Value="D:\Pictures\on_me.png"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Image.Style>
                    </Image>
                </StackPanel>
            </Button>
        </Grid>

    C#

        public partial class MainWindow : Window
        {
            bool status = false;
            
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void button1_MouseDown(object sender, MouseButtonEventArgs e)
            {
                if (status == false)
                {
                    status = true;
                }
                else
                {
                    status = false;
                }
            }
        }


    • Edited by Andre_99 Thursday, June 13, 2019 11:50 AM
    Thursday, June 13, 2019 11:49 AM

All replies

  • Two problems.  First status must be a property to be able to bind to it.  In your code it is a field.

    Second you must set the datacontext of the window.  Otherwise binding will not be able to find the property status.


    Lloyd Sheen

    Thursday, June 13, 2019 12:30 PM