[英]How can I set the initial SelectedItem for a ComboBox bound to an enum, to a Value of an object containing that enum?
[英]Set Value of Enum Bound ComboBox Programatically
我正在使用: 将枚举属性数据绑定到WPF数据组合框中的ComboBox。 我无法以编程方式设置组合框的值。 一旦绑定,就无法设置SelectedItem,SelectedValue或Text。
一定有办法做到吗? 任何帮助表示赞赏。
为了澄清,我有一个绑定到具有所有50个状态的枚举的comboBox。 我有一个与comboBox绑定到的枚举类型相同的状态值。 我想将comboBox值设置为我的状态值。
如果将ComboBox的SelectedItem绑定到基础类,则应该能够通过更改该类来更改绑定。
例如,假设您的枚举名为“ Country”,并且您有一个名为“ Person”的类,并且该人具有一个名为“ CountryOfOrigin”的属性,并且您想将其绑定到ComboBox。 您可以这样做:
XAML文件:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestingWPF"
x:Class="TestingWPF.TestWindow">
<Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type local:Country}"
x:Key="Countries">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Country" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<StackPanel>
<ComboBox x:Name="comboBox"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Width="100" Margin="10"
ItemsSource="{Binding Source={StaticResource Countries}}"
SelectedItem="{Binding Path=CountryOfOrigin, Mode=TwoWay}"/>
<Button HorizontalAlignment="Center" Content="Change Country to Mexico" Margin="10" Click="Button_Click"/>
</StackPanel>
</Window>
后台代码:
public partial class TestWindow : Window
{
Person p;
public TestWindow()
{
InitializeComponent();
p = new Person();
p.CountryOfOrigin = Country.Canada;
DataContext = p;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
p.CountryOfOrigin = Country.Mexico;
}
}
public enum Country
{
Canada,
UnitedStates,
Mexico,
Brazil,
}
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Country _countryOfOrigin;
public Country CountryOfOrigin
{
get
{
return _countryOfOrigin;
}
set
{
if (_countryOfOrigin != value)
{
_countryOfOrigin = value;
PropertyChanged(this, new PropertyChangedEventArgs("CountryOfOrigin"));
}
}
}
}
我发现本文在处理与ComboBoxes绑定的枚举时非常有用,还提供了一些示例,该示例如何组织转换以使用其属性值显示枚举。
因此,用户可以看到fe“>”符号,而不是名为Greater的枚举
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.