MVVM-如果选中复选框,则绑定到复选框 [英] MVVM - binding to check box if checkbox checked

查看:103
本文介绍了MVVM-如果选中复选框,则绑定到复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串值绑定到文本框,但前提是选中一个复选框。因此,如果选中了该复选框,则我希望文本框显示消息1,否则显示消息2。

I want to bind a string value to a text box but only if a check box is checked. So, if the checkbox is checked I want the textbox to display Message 1, if not then display Message 2.

执行此操作的最佳方法是什么?最好在我的对象中使用List属性,然后取决于是否选中了复选框,取决于显示在我List中的哪个项目<>

What is the best way to do this? Is it better to use a List property in my object and then depending on if the check box is checked or not depends on which item from within my List<> is displayed

还是

是否最好在选中复选框后才更新对象的属性(这次是字符串类型),然后重新绑定?

is it better to just update the object's property (this time of type string) after the checkbox is selected and then re-bind?

推荐答案

这里是一种MVVM类型的方法,假定您了解INotifyPropertyChanged(您需要!)。

Here is one MVVM type of approach that assumes you understand INotifyPropertyChanged (you need to!). Play with it and feel free to ask about anything you get stuck on.

public class MyViewModel : INotifyPropertyChanged {

    const string Msg1 = "blah 1";
    const string Msg2 = "blah 2";

    private bool _isSelected;
    public bool IsSelected{
        get { return _isSelected; }
        set {
            if(_isSelected == value) return;

            _isSelected = value;
            MyBoundMessage = _isSelected ? Msg1 : Msg2;

            NotifyPropertyChanged(()=> IsSelected);
            NotifyPropertyChanged(()=> MyBoundMessage);
        }
    }

    public string MyBoundMessage {get;set;}
}

V(查看XAML)

<CheckBox IsChecked="{Binding IsSelected}" />
<TextBox Text="{Binding MyBoundMessage}" />

这篇关于MVVM-如果选中复选框,则绑定到复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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