UserControl绑定到Model属性

时间:2016-04-04 14:43:07

标签: c# .net wpf silverlight

我正在增强Silverlight / WPF应用程序。我有一个UserControl,它需要在模型上的属性更改时禁用或启用某些控件。它必须做一些其他逻辑,所以我不能只将它们绑定到属性。

在后面的控件代码中,我有一个对模型的引用。我知道有一种绑定到某些属性的方法,我知道如何在XAML中执行它,但不知道在代码隐藏中。

我见过许多实例说要使用INotifyPropertyChanged接口,但在这种情况下似乎不适用。

我正在尝试做的一个例子:

public partial class MyControl : UserControl
{
    private readonly MyModel _model;

    public MyControl(MyModel model)
    {
        _model = model;
        // bind to model's ImportantThing property here
     }
    ...
    // Some method gets called when property changes
    ...
}

public class MyModel
{
    ...
    public bool ImportantThing
    {
        get { return _importantThing; }
        set
        {
            _importantThing = value;

            // This is existing code and notifies some controls, but not the ones
            // I'm interested in. It should notify MyControl as well. I know in
            // most applications, this is OnPropertyChanged();
            RaisePropertyChanged("ImportantThing");
        }
    }
}

任何指针?

2 个答案:

答案 0 :(得分:1)

Some Pointers....

Your issue\solution sounds like a task for a ValueConverter. But first, I can see code in the UserControl code-behind file, you really should adopt and apply the MVVM pattern... OK there is a [steep] learning curve and sometimes you wonder if it's worth the effort (know I did when I started with XAML)... But take my word for it.... MVVM, there simply in no other way to develop using WPF. If you try to apply the WinForms UI Logic to WPF it will become an unmaintainable, unmanageable monolithic pile of spaghetti code....

you might find this link to Rachel Lim's Blog useful....

https://rachel53461.wordpress.com/category/mvvm/

and for ValueConverter take a look at this.....

http://www.wpftutorial.net/ValueConverters.html

答案 1 :(得分:0)

我道歉,我原来的问题并不是那么清楚,但我找到了解决办法。事实证明UserControl(我的原始示例中为MyControl)已经在观察模型的变化:

_myModel.PropertyChanged += Model_PropertyChanged;

在现有的回调(Model_PropertyChanged())中,我只是寻找我感兴趣的属性并添加了我需要的所有内容:

void Model_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if (e.PropertyName == "StatusEnabled")
    {
        // do stuff
    }
    else if (e.PropertyName == "ImportantThing")
    {
        // my stuff
    }
}

感谢大家的投入!