WPF Listview绑定无法使用Dictionary



我有一个WPF项目,在XAML文件中,我有列表视图并绑定到字典。但每当我更改dictionary值的值时,它就不会绑定回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=视图模型。字母键;

您为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));
}
}
}

最新更新