我的wpf应用程序中有一个切换按钮。启动时,必须设置togglebutton。
我的Xaml文件:
<ToggleButton Content="AUD Reset" IsChecked="True" Height="23" HorizontalAlignment="Center" Margin="0" Name="button4" Command="{Binding Path=ConnectCommand}" VerticalAlignment="Center" Width="100" />
在togglebutton上单击我想检查我的viewmodel类中的切换状态,如果它返回true,那么我想执行以下操作:
我的ViewModel类:
private ICommand mUpdater;
public ICommand ConnectCommand
{
get
{
if (mUpdater == null)
mUpdater = new DelegateCommand(new Action(ConnectToSelectedDevice), new Func<bool>(ConnectCanExecute));
return mUpdater;
}
set
{
mUpdater = value;
}
}
public bool ConnectCanExecute()
{
return true;
}
public void ConnectToSelectedDevice()
{
mComm.SetAddress(0x40);
Byte[] buffer= new Byte[2];
buffer[0] = 0x24;
buffer[1] = 0x00;
if(Check if button togglestate is set, if true then)
{
buffer[1] = 0x04;
}
mComm.WriteBytes(2, buffer);
}
如何在我的viewmodel中检查是否选中了togglebutton并执行上述语句。
请帮忙!!
答案 0 :(得分:2)
您可以将IsChecked属性添加到ViewModel并将其与ToggleButton.IsChecked依赖项属性绑定:
public bool IsChecked {
get { return this.isChecked; }
set {
this.isChecked = value;
this.OnPropertyChanged("IsChecked");
}
}
<ToggleButton Content="AUD Reset" IsChecked="{Binding Path=IsChecked}" Height="23" HorizontalAlignment="Center" Margin="0" Name="button4" Command={Binding Path=ConnectCommand} VerticalAlignment="Center" Width="100" />
然后检查其状态:
public void ConnectToSelectedDevice()
{
mComm.SetAddress(0x40);
Byte[] buffer= new Byte[2];
buffer[0] = 0x24;
buffer[1] = 0x00;
if(this.IsChecked)
{
buffer[1] = 0x04;
}
mComm.WriteBytes(2, buffer);
}
最后,在ViewModel的构造函数中初始化IsChecked属性:
public ViewModel() {
this.IsChecked = true;
}