這裏是解決方案代碼它在XAML中執行所有的操作,而不是後端的C#。這是我該怎麼辦利用MVVM我的項目(減少後端代碼,如果可能的話沒有後端代碼)
<ListBox x:Name="lstServers" HorizontalAlignment="Left" Height="285" Margin="20,37,0,0" VerticalAlignment="Top" Width="215"
ItemsSource="{Binding Settings.Servers}"
SelectedItem="{Binding Settings.ManageSelectedServer, Mode=TwoWay}"
DisplayMemberPath="UserFriendlyName"/>
這是窗口列表框。這裏指出的要點非常棘手,通常的ItemsSource屬性被設置爲我的視圖模型上的Settings對象,該對象具有Servers Observable集合。
服務器是一個具有名爲UserFriendlyName屬性的類。
public sealed class AutoSyncServer : ObservableModel
{
public AutoSyncServer()
{
Port = "80";
UserFriendlyName = "AutoSync Server";
Server = "localhost";
}
private string _userFriendlyName;
public string UserFriendlyName
{
get { return _userFriendlyName;}
set
{
_userFriendlyName = value;
OnPropertyChanged("UserFriendlyName");
}
}
這是您自己的類的部分代碼片段。
ListBox的SelectedItem綁定到我存儲在名爲ManageSelectedServer的模型視圖中的Selected對象的實例。
棘手的部分這裏是DisplayMemberPath設置爲「UserFriendlyName」而不是「{Binding UserFriendlyName}」。 這是密鑰
如果使用{Binding UserFriendlyName},它將在集合中顯示UserFriendlyNames,但不會反映對該屬性的任何更改。
的XAML對TextBox其中用戶可以更新用戶友好名稱(其應該改變在列表框中也文本)是:
<TextBox x:Name="txtDisplayName" HorizontalAlignment="Left" Height="23" Margin="395,40,0,0" TextWrapping="Wrap"
Text="{Binding ElementName=lstServers,Path=SelectedItem.UserFriendlyName, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment =「頂部」 WIDTH =「240」 />
這設置TextBox的Text屬性並將其綁定到ListBox元素lstServers SelectedItem屬性UserFriendlyName。我還包含一個UpdateSourceTrigger = PropertyChanged,以便對文本源進行的任何更改都會通知它們已被更改。
XAML很棘手!