【发布时间】:2018-06-22 16:26:56
【问题描述】:
使用以下代码,我希望组合框恢复为初始 Selected_Item,但它不会,窗口上的 ComboBox 始终显示我选择的任何新项目(并且与模型不同步),我也尝试过始终调用 OnPropertyChanged("Selected_Item");无论值是否不同,组合框仍然显示新选择的项目并且不同步。可能我做错了,但是,正确的方法是什么?
namespace WpfApplication8
{
public class Context : INotifyPropertyChanged
{
#region Privates
bool c_Disabled = false;
#endregion
#region Ctors
public Context()
{
Items = new List<MyItem>();
Items.Add(new MyItem("Item 1"));
Items.Add(new MyItem("Item 2"));
Items.Add(new MyItem("Item 3"));
Selected_Item = Items[0];
c_Disabled = true;
}
#endregion
#region Properties
public List<MyItem> Items
{
get;
private set;
}
private MyItem c_Selected_Item;
public MyItem Selected_Item
{
get { return c_Selected_Item; }
set
{
if (c_Selected_Item != value)
{
if (!c_Disabled)
{
c_Selected_Item = value;
OnPropertyChanged("Selected_Item");
}
}
}
}
#endregion
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string f_Prop_Name)
{
PropertyChangedEventHandler l_Handler = PropertyChanged;
if(null != l_Handler)
{
l_Handler(this, new PropertyChangedEventArgs(f_Prop_Name));
}
}
#endregion
}
public class MyItem
{
public MyItem(string f_Name)
{
Name = f_Name;
}
public string Name {get;set;}
}
}
和下面的窗口:
<Window x:Class="WpfApplication8.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">
<Grid>
<ComboBox
HorizontalAlignment="Center"
VerticalAlignment="Top"
ItemsSource="{Binding Items}"
SelectedItem="{Binding Selected_Item}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
【问题讨论】:
-
c_Disabled 始终为真。
-
您的问题不清楚。很明显,您的 if 条件始终为真。也许如果你清楚地说明你的要求,人们可以建议你哪里出错了。
-
您的
Selected_Item设置器无法阻止 ComboBox 的 SelectedItem 发生变化,即使它没有设置其支持字段。只要绑定没有被重新评估,什么都不会发生。 -
“视图完全忽略了这一点” - 当然,因为您对绑定如何工作的假设是错误的。
-
@Clemens,不,我假设它不起作用,因为我说过 [quote] 我还尝试始终调用 OnPropertyChanged("Selected_Item")[/quote]。这意味着即使我在忽略集合时重新触发属性更新,它也会被 UI 忽略。