![](/img/trans.png)
[英]How to bind a property in the view model of a usercontrol to a property in another usercontrol
[英]UserControl bind to a Model property
我有一個正在增強的 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");
}
}
}
任何指針?
一些指針....
您的問題\\解決方案聽起來像是 ValueConverter 的任務。 但首先,我可以在 UserControl 代碼隱藏文件中看到代碼,你真的應該采用並應用 MVVM 模式......好吧,有一個 [陡峭的] 學習曲線,有時你想知道是否值得付出努力(知道我什么時候做過)我從 XAML 開始)...但請相信我的話.... MVVM,沒有其他方法可以使用 WPF 進行開發。 如果您嘗試將 WinForms UI 邏輯應用於 WPF,它將變成一個無法維護、無法管理的意大利面條式代碼堆......
你可能會發現這個指向 Rachel Lim 博客的鏈接很有用......
https://rachel53461.wordpress.com/category/mvvm/
和 ValueConverter 看看這個.....
抱歉,我最初的問題不是很清楚,但我找到了解決方案。 事實證明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
}
}
感謝大家的投入!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.