我有一個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