我试着寻找这个问题的答案,但我没有任何运气。基本上,我有一个列表视图,它绑定到从视图模型返回的集合。我将列表视图的选定项绑定到我的列表视图中的一个属性,以便执行验证以确保选择了一个项。问题是,有时我想加载这个列表视图,其中一个项目已经被选中。我希望能够用我想要选择的对象在视图模型上设置属性,并让它自动选择该项目。这没发生过。加载我的列表视图时没有选择任何项目。我可以成功地将选定的索引设置为第0个索引,所以为什么我不能设置选定的值。列表视图处于单选模式。
下面是我的列表视图中的相关代码
<ListView Name="listView1" ItemsSource="{Binding Path=AvailableStyles}" SelectionMode="Single">
<ListView.SelectedItem>
<Binding Path="SelectedStyle" ValidatesOnDataErrors="True" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" BindingGroupName="StyleBinding" >
</Binding>
</ListView.SelectedItem>
<ListView.View>
<GridView>
<GridViewColumn Header="StyleImage">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Source="800.jpg"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Style Code" DisplayMemberBinding="{Binding StyleCode}"/>
<GridViewColumn Header="Style Name" DisplayMemberBinding="{Binding StyleName}"/>
</GridView>
</ListView.View>
</ListView>下面是我的视图模型中的相关代码
public class StyleChooserController : BaseController, IDataErrorInfo, INotifyPropertyChanged
{
private IList<Style> availableStyles;
private Style selectedStyle;
public IList<Style> AvailableStyles
{
get { return availableStyles; }
set
{
if (value == availableStyles)
return;
availableStyles = value;
OnPropertyChanged("AvailableStyles");
}
}
public Style SelectedStyle
{
get { return selectedStyle; }
set
{
//if (value == selectedStyle)
// return;
selectedStyle = value;
OnPropertyChanged("SelectedStyle");
}
}
public StyleChooserController()
{
AvailableStyles = StyleService.GetStyleByVenue(1);
if (ApplicationContext.CurrentStyle != null)
{
SelectedStyle = ApplicationContext.CurrentStyle;
}
}
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
string error = string.Empty;
if (columnName == "SelectedStyle")
{
if (SelectedStyle == null)
{
error = "required";
}
}
return error;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}我要指出的是,这里提到的“样式”与WPF无关。它是一个业务对象。我真的在寻找一种不破坏MVVM模式的解决方案,但我愿意让一些东西正常工作。我试图遍历Listview.Items列表,只是为了手动设置它,但当我尝试时,它总是空的。任何帮助都是非常感谢的。
编辑:我更新了代码以使用INotifyPropertyChanged。它还是不起作用。任何其他建议第二次编辑:我添加了UpdateSourceTrigger="PropertyChanged“。这仍然不起作用。
谢谢
发布于 2010-02-19 04:53:45
您的问题很可能是因为您的SelectedItem Style是一个不同的Style实例,而不是ItemsSource中AvailableStyles中匹配的实例。
您需要做的是在Style类中提供您对相等的特定定义:
public class Style: IEquatable<Style>
{
public string StyleCode { get; set; }
public string StyleName { get; set; }
public virtual bool Equals(Style other)
{
return this.StyleCode == other.StyleCode;
}
public override bool Equals(object obj)
{
return Equals(obj as Style);
}
}发布于 2010-02-19 03:17:24
嗯..。看起来您忘记了为SelectedStyle属性实现INotifyPropertyChanged ...
https://stackoverflow.com/questions/2291359
复制相似问题