【问题标题】:Binding Combobox ItemsSource to the StaticResource in the DataTemplate?将 Combobox ItemsSource 绑定到 DataTemplate 中的 StaticResource?
【发布时间】:2014-03-17 15:58:43
【问题描述】:

我有一个combobox,我想在其中显示几个对象并返回enum 值。根据外部数据在视图中生成combobox的随机数。 combobox 按预期工作,但是在我打开它们中的任何一个然后打开另一个之后,然后是我第一次打开的那个,然后第一个中的项目无法访问。(这些项目仍然存在,但 @987654325 @ 菜单为空)。

为了清楚起见,我一步一步地把我的行动放在这里:

  1. 我打开ComboBox1。我可以看到所有项目。
  2. 我打开ComboBox2。我可以看到所有项目。
  3. 我尝试打开ComboBox1。它的下拉菜单中没有任何项目。
  4. 我打开ComboBox3。我可以看到所有项目。
  5. 所有项目都从ComboBox1ComboBox2 中消失。

我猜这个问题是由ItemsSource 的路径损坏引起的,但我不知道如何避免它。

<DataTemplate x:Key="CustomizedComboBox">
<StackPanel Width="70" Margin="0,0,12,0">
  <ComboBox 
      SelectedIndex="{Binding Path=Type, Mode=TwoWay, Converter={vm:SelectedItemConverter}}" 
      ItemsSource="{StaticResource IconsAndLabelsArray}" 
      MinHeight="50"/>
  </ComboBox>
</StackPanel>

IconsAndLabelsArray:

<x:Array x:Key="IconsAndLabelsArray" Type="{x:Type StackPanel}" >
    <StackPanel Orientation="Horizontal">
      <Image Height="42"
             VerticalAlignment="Top"
             Source="/ProjectName;image1.png"
             Stretch="Uniform" />
      <Label VerticalAlignment="Center" Content="Image1 Label" />
    </StackPanel>
    <StackPanel Orientation="Horizontal">
      <Image Height="42"
             VerticalAlignment="Top"
             Source="/ProjectName;image2.png"
             Stretch="Uniform" />
      <Label VerticalAlignment="Center" Content="Image2 Label" />
    </StackPanel>       

【问题讨论】:

    标签: wpf vb.net xaml combobox datatemplate


    【解决方案1】:

    IconsAndLabelsArray 上设置x:Shared="False",以便为每个组合框创建新资源,而不是使用以前的资源。

    <x:Array x:Shared="False" x:Key="IconsAndLabelsArray"
             Type="{x:Type StackPanel}" >
      ....
    </x:Array>
    

    问题是 Visual 在添加到另一个 Visual 父级之前必须断开连接。这就是为什么上次打开的组合框总是赢的原因,因为默认情况下资源是共享的。因此是一个问题。

    将共享设置为 false 将为每个组合框提供新的资源实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-11
      • 1970-01-01
      • 2018-08-02
      • 2017-01-05
      • 2011-12-09
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多