[英]Wpf Binding Confusion
我正在嘗試學習MVVM。 我了解這個概念,但是我對綁定感到困惑。 我不確定在哪里綁定我的Fill屬性。 請幫忙。 Tqvm高級。
視圖-名稱:MainScreen.xaml
<Path Fill="{Binding mainScreenClass, Converter={StaticResource colorConverter}}"/>
inCodeBehind
DataContext = new vmMainScreen();
ViewModel-名稱:vmMainScreen
public ICommand cmdMouseEnterNav { get; private set; }
public mMainScreen mainScreenClass { get; set; }
public vmMainScreen()
{
mainScreenClass = new mMainScreen();
mainScreenClass.propNaviconFill = new SolidColorBrush(Colors.White);
naviconMouseEventChecker();
}
private void naviconMouseEventChecker()
{
cmdMouseEnterNav = new SimpleCommand
{
ExecuteDelegate = x => mainScreenClass.propNaviconFill = (SolidColorBrush)(new BrushConverter().ConvertFrom("#c5a02b"))
};
}
型號-名稱:mMainScreen
public class mMainScreen : INotifyPropertyChanged
{
private Brush _NaviconFill = new SolidColorBrush(Colors.White);
public Brush propNaviconFill
{
get
{
return this._NaviconFill;
}
set
{
this._NaviconFill = value;
NotifyPropertyChanged("propNaviconFill");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
我了解到當我在colorConverter上斷點時,我正在上課。 不是propNaviconFill的屬性。 如果我在ViewModel上使用Brush類創建另一個屬性並將其綁定到Fill,就沒有問題。 但這意味着我沒有遵循正確的MVVM結構。 再次感謝。
您應該綁定到視圖模型的屬性。
<Path Fill="{Binding propNaviconFill, Converter={StaticResource colorConverter}}"/>
使用將INotifyPropertyChanged
實現為視圖的數據上下文的視圖模型。
DataContext = new mMainScreen();
如果您確實要使用vmMainScreen
作為數據上下文,則vmMainScreen
應該在那里實現INotifyPropertyChanged
,並且您應該研究如何使用NotifyPropertyChanged
通知視圖視圖模型屬性已更改。
請記住,MVVM有兩種基本類型:1.首先查看2.首先查看模型
根據您的示例,您嘗試執行“視圖優先”。 這易於實現,但在較大的項目中也有缺點,因為視圖控制着ViewModel的創建,因此很難將數據或狀態注入到ViewModel中。
對於所有MVVM模式,您可以分為三個部分:
模型 -基本上是一個狀態包。 這件事就像大多數情況下實現INotifyProperty更改的客戶類。
ViewModel-類似於MVC中的控制器類。 它具有所有真實的邏輯並可以正常工作。
視圖 -這是您的XAML,僅包含表示邏輯。 如果要使用View First,則不應使用代碼隱藏類(即MyWindow.xaml.cs),除非要設置ViewModel。 (當然也有例外,但通常基本上應該是空的)
對於“首先查看”,您的窗口(或控件)應在構造函數中創建ViewModel並將其分配給DataContext。
您的ViewModel將具有ICommand的ObservableCollections,並且可以綁定到View中的控件。 因此,當您的構造函數觸發時,您會填充數據並將其放入必要的結構中; 由於數據綁定,它與視圖相關並顯示。
您的模型(通常有多個模型,可以有Customer,Order,StockTicker或其他任何東西。)這些模型是由ViewModel創建的,並放入諸如ObservableCollections之類的東西供View進行數據綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.