【问题标题】:C# WPF Combobox TextElement.Foreground BindingC# WPF 组合框 TextElement.Foreground 绑定
【发布时间】:2019-01-20 08:02:27
【问题描述】:

我希望将我的组合框的TextElement.Foreground 属性链接到我的对象的变量:"ALV_COULEUR""tValeur"

我在输出中注意到它没有找到变量 ALV_COULEUR ...

System.Windows.Data 错误:40:BindingExpression 路径错误: 在“对象”“属性”上找不到“ALV_COULEUR”属性 (哈希码=35307513)'。绑定表达式:路径=ALV_COULEUR; DataItem='属性' (HashCode=35307513);目标元素是“组合框” (名称='');目标属性是“前景”(类型“画笔”)

链接的对象是值而不是“属性”...

这种情况下不能绑定吗?

谢谢!

<ComboBox IsEditable="True"
          TextElement.Foreground="{Binding ALV_COULEUR, Converter={StaticResource IntToBrushConverter}, Mode=OneWay}"
          ItemsSource="{Binding tValeur, Mode=OneWay}" SelectedValuePath="ALV_ID" DisplayMemberPath="ALV_VALEUR"
          SelectedValue="{Binding ATT_VALEUR, Converter={StaticResource StringToIntConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          IsEnabled="{Binding IsEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
</ComboBox>

编辑:

我的课:

public class Attribut
{
    public int                      ATT_ID          { get; set; }
    public string                   ATT_LIBELLE     { get; set; }

    public List<ValeurAttribut>     tValeur         { get; set; }
}

public class ValeurAttribut
{
    public int      ALV_ID      { get; set; }
    public string   ALV_VALEUR  { get; set; }
    public int      ALV_COULEUR { get; set; }
}

DataContext : DataGrid 链接到 ObservableCollection&lt;Attribut&gt;()

【问题讨论】:

  • 它失败了,因为您的数据上下文不正确。您能否展示如何为您的 ComboBox(和父对象)提供数据上下文?
  • @JamesHarcourt 我编辑了带有课程描述的帖子
  • @WDKyle:为什么没有在 Attribut 类中定义 ALV_COULEUR 属性?或者您希望 ComboBox 中的每个项目都使用不同的颜色?
  • @mm8:是的,对于每个项目。

标签: c# wpf xaml combobox binding


【解决方案1】:

使用TextBlock 定义ItemTemplate 并将其Foreground 属性绑定到您的ALV_COULEUR 源属性。还将 TextBlock.Foreground 绑定到ComboBoxSelectedItem 属性:

<ComboBox IsEditable="True"
          TextBlock.Foreground="{Binding SelectedItem.ALV_COULEUR, Converter={StaticResource IntToBrushConverter}, RelativeSource={RelativeSource Self}}">
          ItemsSource="{Binding tValeur, Mode=OneWay}" SelectedValuePath="ALV_ID" DisplayMemberPath="ALV_VALEUR"
          SelectedValue="{Binding ATT_VALEUR, Converter={StaticResource StringToIntConverter}, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          IsEnabled="{Binding IsEnabled, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding ALV_VALEUR}" Foreground="{Binding ALV_COULEUR, Converter={StaticResource IntToBrushConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

【讨论】:

  • 我已经测试过了,但它不起作用,因为我的组合框是可编辑的。所以如果我放一个文本块,我什么都抓不到。
  • 我不关注。您可以复制所选项目的文本,不是吗?这种方法应该适用于可编辑的组合框。你试过了吗?
  • 是的,我说得不好。它适用于可选项目,但对于作为文本框的选定项目,它保持黑色。使用 TextElement.Foreground 一切都很好。
  • 好!有义务为所选项目和其他项目单独管理吗?谢谢:)
  • 我才发现输入文字时颜色变回黑色:(
猜你喜欢
  • 2015-04-27
  • 2014-02-03
  • 2011-08-25
  • 2012-06-18
  • 2011-03-09
  • 1970-01-01
相关资源
最近更新 更多