开发者

C#, XAML, WPF: Best way to do complex binding including textboxes and checkboxes

开发者 https://www.devze.com 2023-03-23 02:53 出处:网络
I have two textboxes and one checkbox (and other similar cases), wh开发者_JAVA技巧ere I want the underlying dataobjects (two ints) which my program will later be using to be equal to what\'s in the te

I have two textboxes and one checkbox (and other similar cases), wh开发者_JAVA技巧ere I want the underlying dataobjects (two ints) which my program will later be using to be equal to what's in the textboxes unless the checkbox is checked, they should in that case be 0 and Int.max respectively.

What's the best way to do this with WPF bindings? I assume I have to use multibindings somehow? The other possibility would be to chain values together if that's even possible (?), i.e. checkbox.IsChecked binds to textBox.Text via some custom converter, which binds to the underlying dataobject.

How would you do this? Seems to me that multibindings make sense where multiple things affect one other thing cumulatively somehow and that chaining makes more sense wherever possible, right? I have one case which is similar to the above but also includes a Slider.


The easiest way is to use the MVVM approach. Build a ViewModel that implements the logic you need:

public class MyViewModel : ViewModelBase
{
    private int _min;
    public int Min
    {
        get { return _min; }
        set
        {
            _min = value;
            OnPropertyChanged("Min");
            OnPropertyChanged("ActualMin");
        }
    }

    private int _max;
    public int Max
    {
        get { return _max; }
        set
        {
            _max = value;
            OnPropertyChanged("Max");
            OnPropertyChanged("ActualMax");
        }
    }

    private bool _useMinMax;
    public bool UseMinMax
    {
        get { return _useMinMax; }
        set
        {
            _useMinMax = value;
            OnPropertyChanged("UseMinMax");
            OnPropertyChanged("ActualMin");
            OnPropertyChanged("ActualMax");
        }
    }

    public int ActualMin
    {
        get { return _useMinMax ? _min : 0; }
    }

    public int ActualMax
    {
        get { return _useMinMax ? _max : int.MaxValue; }
    }

}

Bind your textboxes to Min and Max, and bind the CheckBox to UseMinMax. Then use ActualMin and ActualMax to get the actual values to use.


I'd use the MVVM approach. In the view-model layer you may put whatever logic you want to make the UI behaving according your goals. Simple, fast and reliable.


You could use MVVM. Here you have it, on video plus free:

http://windowsclient.net/learn/video.aspx?v=288066

0

精彩评论

暂无评论...
验证码 换一张
取 消