[英]Updating the DisplayMember of a ListBox
這個問題涉及一個小小的Winforms GUI。 眾所周知,我具有數據綁定和INotifyPropertyChanged的基本知識,並且在WPF的ViewModel中都可以使用它們。 但是我不知道Winforms。 這是用於學校作業。
所以我有一個具有DisplayName
屬性的類。 我還有一個ListBox
其Items
是類的實例序列。 我已經指出myListBox.DisplayMember = "DisplayName";
在更改類實例的值之后,該值將導致DisplayName
屬性返回不同的值,如何告訴ListBox
再次拉DisplayName
屬性以刷新其值?
我需要做同樣的事情,但是要使用組合框。 我發現的解決方法是清除並重置DisplayMember屬性。
這工作:
myComboBox.DisplayMember = null;
myComboBox.DisplayMember = "DisplayName";
重要的是要注意,這可能不是最佳解決方案,因為它將導致多個SelectedValueChanged事件,但最終結果是成功的。
以這種方式執行此操作可能需要重新綁定列表框,失去selectedIndex等。
一種解決方法是忘記DisplayMember屬性,而處理ListBox的Format事件。 類似於(從內存中):
// untested
e.Value = (e.Item as MyClass).DisplayValue;
我知道這已經有很長時間了,但是我遇到了類似的問題,無法找到令人滿意的解決方案,並在更新值后最后用這行代碼解決了:
bindingsource.EndEdit();
列表框上的項目反映單擊“更新”按鈕后輸入到文本框的所有更改。 所以像這樣的行之后:
textbox1.DataBindings["Text"].WriteValue();
textbox2.DataBindings["Text"].WriteValue();
只需插入以下行:
bindingsourcevariable.EndEdit();
希望這對也遇到類似問題但仍未找到正確解決方案的人有所幫助
這是解決方案代碼,可完成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,但不會反映對該屬性的任何更改。
用戶可以在其中更新用戶友好名稱(也應更改列表框中的文本)的TextBox的XAML是:
<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 =“頂部”寬度=“ 240” />
這將設置TextBox的Text屬性,並將其綁定到ListBox元素lstServers SelectedItem屬性UserFriendlyName。 我還包括了UpdateSourceTrigger = PropertyChanged,以便對文本源進行的任何更改都將通知它們已被更改。
XAML非常棘手!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.