【问题标题】:How to Bind to a List inside an Observable Collection in WPF如何在 WPF 中绑定到可观察集合内的列表
【发布时间】:2015-10-21 07:18:17
【问题描述】:

我有一个有 2 个公共变量的类,一个字符串和一个自定义类的列表。

我已经设置了绑定,它对字符串很有效,但我无法将它绑定到列表。

代码背后

public class RegKey
{
    public string Name { get; set; }
    public List<CEKeys> Key = new List<CEKeys>();
}

public class CEKeys
{
    public string Path { get; set; }
    public string KeyName { get; set; }
    public string Value { get; set; }
    public string Type { get; set; }
}

XAML

<DataGrid x:Name="dgRegKeys" Margin="0,0,0,40" ItemsSource="{Binding}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Foreground="Black" Width="60" Header="Name" Binding="{Binding Name, Mode=TwoWay}" IsReadOnly="True" />
        <DataGridTextColumn Foreground="Black" Width="140" Header="Value"  Binding="{Binding Path=Key.Value, Mode=TwoWay}" IsReadOnly="False"/>
        <DataGridTextColumn Foreground="Black" Width="140" Header="Type"  Binding="{Binding Path=Key.Value, Mode=TwoWay}" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

如何在使值可编辑的同时绑定到 CEKey 列表?确认值后,我将创建列出的键。

在键入此内容时,我遇到了第二个问题。每个 regkey 都有一个密钥列表。这是因为 RegKey 可能需要设置多个键才能正常工作。我怎样才能同时显示列表中的所有键?

【问题讨论】:

  • 您是如何向此名称和列表添加值的?

标签: c# wpf data-binding wpfdatagrid


【解决方案1】:

列表是字段不是属性,只能绑定属性,需要使用:

public class RegKey
{
   public string Name { get; set; }
   public List<CEKeys> Key { get; set; }

   public RegKey()
   {
        Key = new List<CEKeys>();
   }
}

【讨论】:

  • 我这样做了,但仍然无法正常工作。数据网格显示名称属性,但不显示列表中的任何内容。
  • @mac_attack18 运行程序并查看 Visual Studio 输出窗口,您应该会在那里找到绑定错误消息
  • BindingExpression 路径错误:在 'object' ''List1' BindingExpression:Path=Key.Name; DataItem='RegKey; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') System.Windows.Data Error: 40 : BindingExpression path error: 'Value' property not found on 'object' ''List1' 上未找到 'Name' 属性 我收到这两个值的错误 它定义为 List1 是什么?
  • 键对象没有“名称”属性。具有“名称”属性的是 RegKey。
【解决方案2】:

如果您想将其添加到列表中,您可以很容易地做到这一点:

public class RegKey
    {
        public string Name { get; set; }
        public List<CEKeys> Key = new List<CEKeys>();
        Dictionary<string, List<CEKeys>> dictionary = new Dictionary<string, List<CEKeys>>();
        public RegKey()
        {
            Key = new List<CEKeys>();

            dictionary.Add(Name, Key);
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 2013-05-21
    • 1970-01-01
    • 2011-02-16
    • 2016-11-08
    • 2015-03-07
    • 2010-11-18
    • 1970-01-01
    相关资源
    最近更新 更多