[英]WPF Listview binding not working with Dictionary
我有一個WPF項目,在XAML文件中,我有一個listview並綁定到字典。 但是,每當我更改字典值的值時,它都不會綁定回UI。 誰能幫忙。
我的代碼示例如下所示。
.XAML文件:
<DockPanel Grid.Row="1" Grid.Column="0">
<Border BorderBrush="SkyBlue" BorderThickness="1,1,1,1"></Border>
<StackPanel>
<ListView Margin="0" ScrollViewer.HorizontalScrollBarVisibility="Hidden" Name="lvAlphaKeys" BorderThickness="0" ItemsSource="{Binding AlphaKeys, Mode=TwoWay}" >
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding Key}" Width="30" FontWeight="Bold" />
<TextBlock Text="{Binding Value.DispalyName, Mode=TwoWay}" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</DockPanel>
查看模型:
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Dictionary<string, MyCommand> _AlphaKeys;
public Dictionary<string, MyCommand> AlphaKeys
{
get { return _AlphaKeys; }
set
{
_AlphaKeys = value;
OnPropertyChanged(new PropertyChangedEventArgs("AlphaKeys"));
}
}
}
public class MyCommand
{
public string DispalyName { get; set; }
public string DisplaySymbol { get; set; }
}
.XaML.CS文件:
//Field declaration
MyViewViewModel viewModel;
//Constructur
viewModel = new MyViewViewModel();
DataContext = viewModel;
//Event
viewModel.AlphaKeys[key].DispalyName = "new value";
如果我將itemsource設置為null,然后重新分配列表值的Itemsource,它將正常工作,否則將無法正常工作,有人可以幫忙嗎? lvAlphaKeys.ItemSource = null; lvAlphaKeys..ItemSource = viewModel.AlphaKeys;
您為AlphaKeys
設置了事件,如果集合發生了更改,它將引發一個事件,而不是其項目。
您必須為MyCommand
設置INotifyPropertyChanged
,
public class MyCommand : INotifyPropertyChanged
{
private string _dispalyName ;
public string DispalyName
{
get { return _dispalyName ; }
set
{
_dispalyName = value;
NotifyOfPropertyChange("DispalyName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyOfPropertyChange(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.