【发布时间】:2016-04-27 21:09:18
【问题描述】:
我找到了很多关于如何将 WPF 复选框的 IsChecked 属性绑定到布尔属性的示例,如果两者都属于同一个 Window 类。我想做不同的事情:
我有主窗口(摘录):
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private readonly SoundFx _soundFx = new SoundFx();
private void _StartNewGame()
{
_soundFx.GameStarted();
}
}
然后我有 SoundFx 类(摘录):
public class SoundFx : DependencyObject
{
public void GameStarted()
{
if (Enabled)
{
_PlayGameStartedSound();
}
}
public bool Enabled
{
get { return (bool) GetValue(EnabledProperty); }
set { SetValue(EnabledProperty, value); }
}
public static readonly DependencyProperty EnabledProperty =
DependencyProperty.Register("Enabled", typeof(bool),
typeof(SoundFx), new UIPropertyMetadata(false));
}
我有 XAML(摘录):
<Grid>
<CheckBox IsChecked="{Binding ElementName=_soundFx, Path=Enabled}" x:Name="checkBoxSoundFx" Content="Sound FX" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom"/>
</Grid>
说实话,我是 WPF 的新手,不知道自己在做什么。我想要实现的是,当用户单击checkBoxSoundFx 元素时,_soundFx.Enabled 的值会被更改,而不使用像Checked 或Unchecked 这样的任何事件处理程序。这应该可以通过数据绑定来实现,不是吗?
【问题讨论】:
标签: c# wpf xaml checkbox data-binding