c# - 无法填充 DataGrid

标签 c# wpf mvvm data-binding datagrid

我正在尝试构建一个动态生成列的数据网格(这工作正常),但我无法为自动更新的列创建绑定(bind)(类似于 INotifyPropertyChanged)。

动态创建列并希望使用可以动态修改/添加的字典元素进行绑定(bind)。在 visual studio 的调试输出中没有看到错误。

我想我真的遗漏了一些小东西。

点击按钮不会填充第二列

clicking button does not populate anything

View 模型:

class DataGridAttachedPropertyViewModel {


    public ObservableCollection<DataGridColumn> ColumnCollection { get; set; }
    public ObservableCollection<AttachedPropertyEmployee> SomEmployees { get; set; }

    public ICommand myCommand { get; set; }
    public DataGridAttachedPropertyViewModel() {

        this.ColumnCollection = new ObservableCollection<DataGridColumn>();


        DataGridTextColumn tc = new DataGridTextColumn();
        tc.Header = "Sample Column";
        // tc.Binding = new Binding("name");
        Binding forCurrent =  new Binding("SimpleDict[f]");
        forCurrent.Mode = BindingMode.TwoWay;
        tc.Binding = forCurrent;

        DataGridTextColumn tt = new DataGridTextColumn();
        tt.Header = "Column x";
        // tc.Binding = new Binding("name");
        Binding forTheCurrent = new Binding("SimpleDict[x]");
        forTheCurrent.Mode = BindingMode.TwoWay;

        tt.Binding = forTheCurrent;

        myCommand = new DelegateCommand(ButtonBase_OnClick);

        this.ColumnCollection.Add(tc);
        this.SomEmployees = new ObservableCollection<AttachedPropertyEmployee>();
        this.SomEmployees.Add(new AttachedPropertyEmployee("Rajat","Norwalk"));

        this.SomEmployees.Add(new AttachedPropertyEmployee("Matthew", "Norwalk"));
    }

    public void ButtonBase_OnClick() {
        foreach (var VARIABLE in SomEmployees) {
            VARIABLE.SimpleDict["x"] = "x";
        }
    }

}

AttachedPropertyEmployee.cs

  public class AttachedPropertyEmployee : INotifyPropertyChanged {

    private Dictionary<string, string> dict;

    public Dictionary<string, string> SimpleDict {
        get { return this.dict; }
        set
        {
            if (this.dict != value) {
                this.dict = value;
                this.NotifyPropertyChanged("SimpleDict");
            }
        }
    }

    public AttachedPropertyEmployee(string Name, string Address) {
        this.SimpleDict = new Dictionary<string, string>();
        SimpleDict["f"] ="b";
        this.name = Name;
        this.address = Address;
    }

    public string name;
    public string address { get; set; }


    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propName) {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

XAML:

<Window x:Class="LearnInteractivity.LearnDataGridAttachedProperty"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:LearnInteractivity"
    mc:Ignorable="d"
    Title="LearnDataGridAttachedProperty" Height="300" Width="300">

<!--
Put a datargrid and an attached property and update columns dynamincally. 

-->


<StackPanel>

    <DataGrid 
 local:DataGridColumnsBehavior.BindableColumns="{Binding ColumnCollection}"
        x:Name="dgg"
        AutoGenerateColumns="False" 
        ItemsSource="{Binding SomEmployees}"></DataGrid>
    <Button Content="Populate" Command="{Binding myCommand}"></Button>

</StackPanel>

最佳答案

我在这里看到两个问题。

第一个是Dictionary<TKey,TValue>没有实现 INotifyCollectionChanged ,因此当您更改其中的值时,不会引发任何事件并且 UI 永远不会知道它。你可以找一个 ObservableDictionary<K,V>并使用它(IIRC 周围有一些实现),或者你可以用快速而肮脏的方式来做:

public void ButtonBase_OnClick() {
    foreach (var VARIABLE in SomEmployees) {
        VARIABLE.SimpleDict["x"] = "x";
        VARIABLE.NotifyPropertyChanged("SimpleDict");
    }
}

这将通知网格 SimpleDict已经改变。

第二个问题是在DataGridAttachedPropertyViewModel构造函数,你忘了添加 ttColumnCollection .

    this.ColumnCollection.Add(tc);
    this.ColumnCollection.Add(tt);

更多想法:

我会更愿意将这样的内容添加到 AttachedPropertyEmployee :

public void SetColumValue(string key, string value) {
    SimpleDict[key] = value;
    NotifyPropertyChanged("SimpleDict");
}

然后在你的循环中使用它:

public void ButtonBase_OnClick() {
    foreach (var VARIABLE in SomEmployees) {
        VARIABLE.SetColumnValue("x", "x");
    }
}

顺便说一下,我会更改 SimpleDictDictionary<String, Object>所以你可以支持更多类型而不仅仅是字符串,并将格式留给 UI。我可能会考虑公开一个 ReadOnlyDictionary<K,V>SimpleDict属性,可写字典是一个私有(private)字段——因此调用者别无选择,只能使用 SetColumnValue(k,v)设置列值。

关于c# - 无法填充 DataGrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40182075/

相关文章:

c# - 关于 IEnumerable 的延迟执行

c# - 程序不包含适合入口点的静态 'main' 方法

c# - 在 WPF 中使用 ICommand

WPF MVVM : ICommand Binding to controls

mvvm:我应该如何将 bool 值绑定(bind)到组合框

c# - 与 Caliburn Micro 问题的深度属性绑定(bind)

c# - 在 Windows Phone 应用程序中格式化 MVVM 中的数据

c# - 将二进制文件读入结构

c# - 需要考虑我的面试问题 - .net,c#

c# - 在 dotNET C# 中使用 GZipStream 的正确方法