【问题标题】:How can I stop an implicit TextBox style from getting inherited in a ComboBox when DisplayMemberPath is not set?未设置 DisplayMemberPath 时,如何阻止隐式 TextBox 样式在 ComboBox 中继承?
【发布时间】:2012-08-30 19:36:53
【问题描述】:

我有两个ComboBoxes。一个绑定到枚举值列表,而另一个绑定到自定义类对象列表并具有DisplayMemberPath 属性集。

绑定到枚举值的ComboBox 应用隐式TextBlock 样式,而使用DisplayMemberPath 属性的ComboBox 则没有。

使用Snoop,我可以验证ComboBoxes 是使用完全相同的一组控件呈现的(<ContentPresenter> 包含<TextBlock>),但是ComboBox 中的TextBlock 没有@987654335 @ set 包含一个为 5 的 Margin,而带有 DisplayMemberPath set 的那个则没有。

<Grid.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Margin" Value="5" />
    </Style>
</Grid.Resources>

<ComboBox Grid.Row="0" Grid.Column="1" 
          ItemsSource="{Binding EnumCollection}" 
          SelectedItem="{Binding SelectedEnum}" />

<ComboBox Grid.Column="1" Grid.Row="2" 
          ItemsSource="{Binding SomeCollection}" 
          SelectedItem="{Binding SelectedItem}"
          DisplayMemberPath="Name" />

这是为什么?我该怎么做才能阻止 Enum ComboBox 继承隐式 TextBlock 样式?

【问题讨论】:

  • 我的假设是DisplayMemberPath 创建了一个DataTemplate,样式不会在其范围内应用。
  • @H.B.它确实...每MSDN“此属性是定义描述如何显示数据对象的默认模板的简单方法”。我知道我可以用&lt;ComboBox.Resources&gt; 做一些令人讨厌的丑陋解决方法,但我希望有一个更清洁的解决方案。
  • @KDiTraglia 这将使ComboBoxes 都继承隐含的TextBlock 样式,而我想要相反:让他们两个继承它。

标签: wpf styles implicit-style


【解决方案1】:

我的假设是DisplayMemberPath 创建一个DataTemplate,并且样式不会在其范围内应用。

尝试设置DisplayMemberPath="." 以使第一个ComboBox 使用包含&lt;TextBlock Text="{Binding .}"&gt;DataTemplate,这将阻止应用隐式样式。

【讨论】:

  • 我知道你会知道这个问题的答案 ^_^ 很好,谢谢
  • 这更像是我猜的:)
  • 这没有错 :) 我发现我的编程中有很大一部分只是有根据的猜测。或者正如我所说,“受过教育的试错法”。
  • @Rachel:嗯,如果你对系统有深入的了解,猜测就会变成预测。在这里我只是认为DisplayMemberPath 导致{Binding &lt;VALUE&gt;} 所以{Binding .} 应该可以工作。
猜你喜欢
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多