Rohit
Rohit

Reputation: 10236

How to bind boolean value to label

I am new to WPF. My code is as follows:

In my MainWindow.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="10*"/>
        <RowDefinition Height="50"/>
    </Grid.RowDefinitions>
    <Label HorizontalAlignment="Left" Margin="63,30,0,0" Grid.Row="0" VerticalAlignment="Top" Content="{Binding myVal}" Height="39" Width="71"/>
    <Button Grid.Row="1" x:Name="btnSelect" Content="Select" Click="btnSelect_Click_1" Margin="396,0,10,0"/>
</Grid>

and MainWindow.cs

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private bool _myboolVal;
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void btnSelect_Click_1(object sender, RoutedEventArgs e)
    {
        if (myVal== false)
        {
            myVal = true;
        }
        else
        {
            myVal= true;
        }
    }

    public bool myVal
    {
        get { return _myboolVal; }
        set { _myboolVal= value; OnPropertyChanged("myVal"); }
    }

    private void OnPropertyChanged(string p)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(p));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

But the value of the label is always false.

Upvotes: 0

Views: 935

Answers (3)

Mohan Tangella
Mohan Tangella

Reputation: 19

Please set the Mode to TwoWay ,then it will works.

Content="{Binding myVal,Mode=TwoWay}"

Upvotes: 0

d.moncada
d.moncada

Reputation: 17392

Your logic in btnSelect_Click_1 is incorrect. Update it to:

private void btnSelect_Click_1(object sender, RoutedEventArgs e)
{
    myVal = !myVal;
}

Upvotes: 2

martavoi
martavoi

Reputation: 7082

take a look at this sample (MVVM, Command binding, MVVMLight)

Upvotes: 0

Related Questions