WPF 绑定问题

本文关键字:问题 绑定 WPF | 更新日期: 2023-09-27 18:33:51

我正在使用 WPF 工具包的图表,但在将其绑定到我的 ViewModel 时遇到问题。 什么都没有出现。 我有 MainWindow.DataContext = MainWindowViewModel,如果你想知道的话。 这是我所拥有的:

MainWindow.xaml

<chartingToolkit:Chart Grid.Row="2">
    <chartingToolkit:ColumnSeries Name="line_chart" 
                                  IndependentValuePath="Key"
                                  DependentValuePath="Value" 
                                  ItemsSource="{Binding Me}"/>
</chartingToolkit:Chart>

主窗口视图模型.cs

class MainWindowViewModel
{
    public List<KeyValuePair<string, int>> Me { get; set; }
    public MainWindowViewModel(Model model)
    {
        this.model = model;
        me.Add(new KeyValuePair<string, int>("test", 1));
        me.Add(new KeyValuePair<string, int>("test1", 1000));
        me.Add(new KeyValuePair<string, int>("test2", 20));
        me.Add(new KeyValuePair<string, int>("test3", 500));
    }
    Model model;
    List<KeyValuePair<string, int>> me = new ObservableCollection<KeyValuePair<string,int>>();
}

WPF 绑定问题

我以前没有使用过该图表工具,但是您绑定到一个公共Me属性,该属性对要向其添加值的私有me字段没有任何引用。

删除私有字段并尝试以下操作:

class MainWindowViewModel
{
    public ObservableCollection<KeyValuePair<string, int>> Me { get; private set; }
    public MainWindowViewModel(Model model)
    {
        this.model = model;
        // Instantiate in the constructor, then add your values
        Me = new ObservableCollection<KeyValuePair<string, int>>();
        Me.Add(new KeyValuePair<string, int>("test", 1));
        Me.Add(new KeyValuePair<string, int>("test1", 1000));
        Me.Add(new KeyValuePair<string, int>("test2", 20));
        Me.Add(new KeyValuePair<string, int>("test3", 500));
    }
}