我是WPF的新手。我的代码如下:
在我的 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>
和 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;
}
但标签的值始终为false
。
答案 0 :(得分:2)
btnSelect_Click_1
中的逻辑不正确。将其更新为:
private void btnSelect_Click_1(object sender, RoutedEventArgs e)
{
myVal = !myVal;
}
答案 1 :(得分:0)
看一下这个sample(MVVM,Command binding,MVVMLight)
答案 2 :(得分:0)
请将模式设置为TwoWay,然后它将起作用。
Content =“{Binding myVal,Mode = TwoWay}”