我有一个ComboBox,其属性ItemsSource和SelectedValue绑定到模型。有时,模型需要将所选项目调整为不同的模型,但是当我在模型中执行该操作时,即使SelectedValue已正确设置(通过snoop和SelectionChanged同时检查,模型值并未反映在视图中事件处理程序)。为什么WPF组合框不能正确反映绑定值?
为了说明问题,这里是一个简单的XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<ComboBox Height="25" Width="120" SelectedValue="{Binding SelectedValue}" SelectedValuePath="Key" ItemsSource="{Binding PossibleValues}" DisplayMemberPath="Value"/>
</Grid>
</Window>
这里是模型:
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
int m_selectedValue = 2;
Dictionary<int, string> m_possibleValues = new Dictionary<int, string>() { { 1, "one" }, { 2, "two" }, { 3, "three" }, {4,"four"} };
public int SelectedValue
{
get { return m_selectedValue; }
set
{
if (value == 3)
{
m_selectedValue = 1;
}
else
{
m_selectedValue = value;
}
PropertyChanged(this, new PropertyChangedEventArgs("SelectedValue"));
}
}
public Dictionary<int, string> PossibleValues
{
get { return m_possibleValues; }
set { m_possibleValues = value; }
}
public MainWindow()
{
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
我所期望的行为是如下:
- 最初,选择两个
- 选择“one” - >组合框显示YS “一个”
- 选择 “二” - >组合框显示 “二”
- 选择 “三化” - >组合框显示 “一个”
- 选择 “四大” - >组合框显示 “四大”
然而,在#4中显示“三”。为什么?模型中的值更改为1(“1”),但View仍显示3(“三”)。
我已经找到了一个解决方法,通过显式更新SelectionChanged事件处理程序中的绑定目标,但这似乎是错误的。是否有另一种方法来实现这一目标?
不应该ComboBox显示模型的当前状态?它可能不直观,但它是正确的显示。这实际上是一个简单的例子。实际使用情况有点复杂,但归结为同一问题 – Rado 2012-04-09 20:46:52
您是否尝试过明确地使SelectedValue双向? {Binding Path = SelectedValue,Mode = TwoWay} – 2012-04-09 21:03:41
@JacobProffitt模式默认为TwoWay,但我只是试图明确设置它,问题依然存在。 – Rado 2012-04-09 21:21:45