【问题标题】:Bind some referenced object properties绑定一些引用的对象属性
【发布时间】:2013-04-09 10:18:38
【问题描述】:

我有一本字典:

private Dictionary<int, ICar> _ICarsDic;

对象 ICar 实际上包含另一个对象列表:

public interface ICar 
{
    int carId { get; set; }
    string carName { get; set; }
    Dictionnary<int,IBrandsDetails> brandsDetails { get; set; }
}

我将此 CarsDic 字典绑定到 DataGrid(之前将其转换为 IEnumerable,但这不是问题的重点,因此此处不显示)。

<DataGrid Name="Cars"
    ItemsSource="{Binding}" 
    SelectedItem="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}, AncestorLevel=2}, Path=SelectedCar, Mode=TwoWay}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Car Id" Binding="{Binding CarId}" IsReadOnly="True" />
        <DataGridTextColumn Header="Car Name" Binding="{Binding carName}" IsReadOnly="True" />
    </DataGrid.Columns>

我的问题是我还想显示 BrandsDetails 中的一些数据(所有汽车通用),例如徽标。但是这个合成器不起作用:

<DataGridTextColumn Header="Full Name" Binding="{Binding BrandsDetails.Logo}" IsReadOnly="True" />

提前感谢您的回答!

【问题讨论】:

    标签: c# wpf binding


    【解决方案1】:

    我认为以下链接将解决您的问题

    http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/

    引用

    绑定到字典可能很棘手。

    这听起来很简单,但在第一次尝试时它永远不会奏效。通常,当您第一次运行您的应用程序时,您看到的不是您为项目创建的漂亮模板,而是看起来像一对键和值的东西。您的绑定工作正常,您只是没有考虑绑定到什么。字典中的每个项目都是一对 (Key,Value),这正是您作为绑定项目得到的。您有两种处理方式,您可以更改 Binding 表达式的标记以包含对 Value 的引用:

    <ComboBox.ItemTemplate>
                 <DataTemplate>
                     <StackPanel Orientation="Horizontal">
                         <TextBlock Text="{Binding Value.Text}"></TextBlock>
                         <TextBlock> = </TextBlock>
                         <TextBlock Text="{Binding Value.Value}"></TextBlock>
                     </StackPanel>
                 </DataTemplate>
             </ComboBox.ItemTemplate>
    

    或者您可以更改控件的绑定表达式以引用字典的 Values 属性:

     <ComboBox Height="23" Margin="0,14,9,0" Name="comboBox1"
                      VerticalAlignment="Top" SelectedValuePath="Key"
                      ItemsSource="{Binding Items.Values}"
                      HorizontalAlignment="Right" Width="120">
    

    现在您已将控件绑定到字典,万岁!

    【讨论】:

    • 嗨,谢谢您的回答,但我认为我的问题不够清楚,因为字典不是问题,因为我“之前将其转换为 IEnumerable”(参见问题) .所以问题更多的是我在 ICars 中有 Brand 对象,我似乎无法访问它的属性。
    • 我打开了另一个问题(我希望更清楚),因为我不知道如何在不影响您答案的情况下更改这个问题。谢谢! stackoverflow.com/questions/15915805/…
    【解决方案2】:

    对于这个答案,我假设您的 DataGrid 已绑定到包含 ICar 实现对象的 Dictionary(您的确切绑定既不清楚又过于复杂)。

    BrandsDetails 绑定失败的原因是属性实际上是Dictionary,而您知道它没有Logo 属性。理想情况下,DataGrid 列应该有一个数据模板,它是某种重复器控件,如 ListView 或另一个 DataGrid,或者使用 MultiBinding 和转换器 - 这是您能够从该属性显示完整 Dictionary 的唯一方法。否则你会在路径中need touseindexing为你的绑定挑出单个项目。

    【讨论】:

    • 嗨,谢谢您的回答,但我认为我的问题不够清楚,因为字典不是问题,因为我“之前将其转换为 IEnumerable”(参见问题) .所以问题更多的是我在 ICars 中有 Brand 对象,我似乎无法访问它的属性。
    • 我打开了另一个问题(我希望更清楚),因为我不知道如何在不影响您答案的情况下更改这个问题。谢谢! stackoverflow.com/questions/15915805/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多