繁体   English   中英

绑定一些引用的对象属性

[英]Bind some referenced object properties

我有一本字典:

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" />

预先感谢您的回答!

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

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

引用

绑定到字典可能很棘手。

听起来很简单,但第一次尝试就无法使用。 通常,当您第一次运行应用程序时,您会看到,而不是为项目创建的漂亮模板,您得到的东西看起来像一对键和值。 您的绑定效果很好,您只是没有想到要绑定到什么。 字典中的每个项目都是一对(键,值),而这正是您作为绑定项目获得的。 您有两种处理方法,可以更改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">

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

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

BrandsDetails绑定失败的原因是该属性实际上是Dictionary ,并且您知道它没有Logo属性。 理想情况下,DataGrid列应具有一个数据模板,该模板是某种中继器控件(如ListView或另一个DataGrid),或者使用MultiBinding和转换器-这是唯一可以从该属性显示完整Dictionary的方法。 否则,您将需要在绑定的路径中使用 索引来挑选单个项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM