【问题标题】:How to bind items in a combobox in XAML如何在 XAML 中绑定组合框中的项目
【发布时间】:2018-08-19 15:11:58
【问题描述】:
<TextBlock FontSize="20" Foreground="{x:Bind ????}">
    <Run Text="{x:Bind Username}"></Run>
    <Run Text=": "></Run>
    <Run Text="{x:Bind Message}"></Run>
</TextBlock>

那是文本块。我的期望是当文本块在组合框中获取字符串时,它将通过该字符串设置前景

<ComboBox 
    x:Name="CBBox" 
    PlaceholderText="Color" 
    Margin="10" 
    HorizontalAlignment="Center" 
    VerticalAlignment="Center">
    <x:String>Red</x:String>
    <x:String>Yellow</x:String>
    <x:String>Green</x:String>
    <x:String>Purple</x:String>
    <x:String>Back</x:String>
</ComboBox>

但我不知道要绑定什么想法?

【问题讨论】:

    标签: c# wpf xaml binding uwp


    【解决方案1】:

    Foreground="{Binding ElementName=CBBox,Path=SelectedItem}"

    <ComboBox 
        x:Name="CBBox" 
        PlaceholderText="Color" 
        Margin="10" 
        HorizontalAlignment="Center" 
        VerticalAlignment="Center">
        <x:String>Red</x:String>
        <x:String>Yellow</x:String>
        <x:String>Green</x:String>
        <x:String>Purple</x:String>
        <x:String>Back</x:String>
    </ComboBox>
    <TextBlock FontSize="20" Foreground="{Binding ElementName=CBBox,Path=SelectedItem}">
        <Run Text="{x:Bind Username}"></Run>
        <Run Text=": "></Run>
        <Run Text="{x:Bind Message}"></Run>
    </TextBlock>
    

    【讨论】:

      【解决方案2】:

      通常,最好的方法是将 ComboBox 绑定到视图模型,然后将视图模型绑定到 TextBlock。

      但是,如果它们在同一范围内(页面、用户控件、模板等),则可以直接绑定它们。你必须在这里使用{Binding},而不是{x:Bind},因为你需要一个转换器。

      您可以像这样绑定 Foreground 属性:

      <TextBox Foreground="{Binding SelectedItem, ElementName=CBBox, Converter={StaticResource StringToColorConverter}" ... />
      

      现在您需要添加一个ValueConverter,并让它将所选字符串转换为画笔并返回。

      这样的事情应该可以工作:

      var colorEnum = (Colors) Enum.Parse(typeof(Colors), value);
      var color = new Color(colorEnum);
      return new SolidColorBrush(color);
      

      【讨论】:

      • 我们在 xaml 后面创建的这个 C# 代码?除了这个,我们应该去哪里?
      • 代码应该放在一个你必须编写的新转换器中。请参阅答案中的链接,以及本教程了解更多详细信息:wpf-tutorial.com/data-binding/…
      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 2013-09-10
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多