简体   繁体   English

如何在XAML中绑定组合框中的项目

[英]How to bind items in a combobox in XAML

<TextBlock FontSize="20" Foreground="{x:Bind ????}">
    <Run Text="{x:Bind Username}"></Run>
    <Run Text=": "></Run>
    <Run Text="{x:Bind Message}"></Run>
</TextBlock>

That is the TextBlock. 那就是TextBlock。 My expectation is when the textblock get the string inside the combobox it will set the foreground through that string 我的期望是,当文本块在组合框中获取字符串时,它将通过该字符串设置前景

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

but I dont know what to bind any idea ? 但我不知道该如何约束任何想法?

Usually, the best approach is to bind the ComboBox to the view model, and then bind the view model to the TextBlock. 通常,最好的方法是将ComboBox绑定到视图模型,然后将视图模型绑定到TextBlock。

However, it's possible to bind them directly, provided they're in the same scope (Page, UserControl, Template, etc.). 但是,可以将它们直接绑定,只要它们处于同一范围(页面,用户控件,模板等)中即可。 You'll have to use {Binding} here, instead of {x:Bind} , since this you'll need a converter. 您必须在这里使用{Binding}而不是{x:Bind} ,因为这将需要一个转换器。

You can bind the Foreground property like this: 您可以像这样绑定Foreground属性:

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

Now you'll need to add a ValueConverter , and get it to convert the selected string to a brush and return it. 现在,您需要添加一个ValueConverter ,并将其转换为将选定的字符串转换为画笔并返回它。

Something like this should work: 这样的事情应该起作用:

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

Foreground="{Binding ElementName=CBBox,Path=SelectedItem}" 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>

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

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