MVVM WPF4.0复选框已通过编程方式选中 [英] MVVM WPF4.0 Checkbox checked programatically

查看:58
本文介绍了MVVM WPF4.0复选框已通过编程方式选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在搜索此内容-尽管在绑定复选框时存在很多问题,但是在以编程方式将复选框设置为选中状态时,我找不到任何东西,而我认为我发现的解决方案没有不行.

XAML:

I''ve searched all over for this - while there is PLENTY on binding a checkbox, I couldn''t find anything on programmatically setting the box as checked, and the solutions that I thought I''d found didn''t work.

The XAML:

<CheckBox Content="" Height="16" HorizontalAlignment="Right" Margin="0,297,118,0" Name="checkBox1" VerticalAlignment="Top"

                  Command="{Binding CheckCommand, Mode=TwoWay}" CommandParameter="{Binding IsChecked}">
        </CheckBox>


VieModel:


The VieModel:

private bool isChecked;
private ICommand checkCommand;
        
public bool IsChecked
        {
            get { return isChecked; }
            set
            {
                isChecked = value;
                OnPropertyChanged("IsChecked");
            }
        }

public ICommand CheckCommand
        {
            get 
            {
                if (checkCommand == null)
                    checkCommand = new CommandBase(i => Checkprocess(i), null);
                return checkCommand; 
            }
            set
            {
                checkCommand = value;
                OnPropertyChanged("CheckCommand");
            }
        }
public void Checkprocess(object sender)
        {
           //this DOES react when the checkbox is checked or unchecked
        }

public MyViwModel()
{
     IsChecked = true;
}


IsChecked和isChecked DO的值变为true,但是checkBox1值保持未选中状态.

我在这里缺少什么明显的东西?


The value of IsChecked and isChecked DO become true, however the checkBox1 value remains unchecked.

What obvious thing am I missing here?

推荐答案

代码几乎完成了.您还可以绑定属性.因此,将XAML更改为:

The code is almost completed. You can also bind properties. So change the XAML to:

<CheckBox Content="" Height="16" HorizontalAlignment="Right" Margin="0,297,118,0" Name="checkBox1" VerticalAlignment="Top"

                  Command="{Binding CheckCommand, Mode=TwoWay}" 

     IsChecked="{Binding Path=IsChecked, Mode=TwoWay}">
</CheckBox>



这会将CheckBox的IsChecked属性绑定到视图模型的IsChecked属性.我已经在命令中删除了CommandParameter.您不需要它,因为可以在视图模型中使用它.IsChecked可以获取CheckBox的选中状态.



This will bind the IsChecked property of the CheckBox to the IsChecked property of your viewmodel. I have removed the CommandParameter in the Command. You won''t need it because in your viewmodel you can use this.IsChecked to get the checked state of the CheckBox.


这篇关于MVVM WPF4.0复选框已通过编程方式选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆