我有一个组合框,我提供了从数据上下文设置的选项和值。 xaml看起来像这样:
<ComboBox HorizontalAlignment="Left" Width="120"
ItemsSource="{Binding Options}"
DisplayMemberPath="Text"
SelectedValuePath="OptionValue"
SelectedValue="{Binding Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
如果值和 OptionValue 是我的datacontext中的int,一切正常。例如:
public class MyDataContext : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public class TextValue
{
private string _Text;
private int _Value;
public TextValue(string text, int value)
{
_Text = text;
_Value = value;
}
public int OptionValue
{
get
{
return _Value;
}
}
public string Text
{
get
{
return _Text;
}
}
}
private TextValue[] _Options = new TextValue[]
{
new TextValue("One", 1),
new TextValue("Two", 2),
new TextValue("Three", 3)
};
public TextValue[] Options
{
get
{
return _Options;
}
}
private int _Value = 1;
public int Value
{
get
{
return _Value;
}
set
{
if (_Value != value)
{
System.Diagnostics.Debug.WriteLine("New value set: " + value);
_Value = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
}
}
但如果值和 OptionValue 改为枚举,则在组合框中不会设置默认值。如果我在组合框中更改选项,则设置值,因此我假设数据绑定有效。为什么会这样?这种奇怪的行为仅在Windows应用商店应用中,如果在WPF应用程序中运行相同的东西工作正常。 Enum的代码:
public class MyDataContext : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public enum Number { One, Two, Three }
public class TextValue
{
private string _Text;
private Number _Value;
public TextValue(string text, Number value)
{
_Text = text;
_Value = value;
}
public Number OptionValue
{
get
{
return _Value;
}
}
public string Text
{
get
{
return _Text;
}
}
}
private TextValue[] _Options = new TextValue[]
{
new TextValue("One", Number.One),
new TextValue("Two", Number.Two),
new TextValue("Three", Number.Three)
};
public TextValue[] Options
{
get
{
return _Options;
}
}
private Number _Value = Number.One;
public Number Value
{
get
{
return _Value;
}
set
{
if (_Value != value)
{
System.Diagnostics.Debug.WriteLine("New value set: " + value);
_Value = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
}
}