我試圖尋找這個答案,但我沒有任何運氣。基本上我有一個listview綁定到從視圖模型返回的集合。我將列表視圖的選定項綁定到我的列表視圖中的一個屬性,以便執行驗證以確保選擇一個項目。問題是,有時我想加載這個列表視圖已經選擇的項目之一。我希望能夠使用我想要選擇的對象在我的視圖模型上設置屬性,並讓它自動選擇該項目。這沒有發生。我的列表視圖加載沒有選擇的項目。我可以成功地將選定的索引設置爲第0個索引,爲什麼我不能設置選定的值。列表視圖處於單選模式。WPF ListView設置SelectedItem
下面是從我的列表視圖
<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);
}
}
}
我要指出的是,「風格」這裏提到有nothign做與WPF。這是一個商業對象。我真的在尋找一種不會破壞MVVM模式的解決方案,但我願意只是爲了實現某種功能。我試圖通過Listview.Items列表循環來手動設置它,但是當我嘗試時它總是空的。任何幫助表示讚賞。
編輯:我更新了代碼以使用INotifyPropertyChanged。它仍然不起作用。任何其他建議 第二編輯:我添加UpdateSourceTrigger =「PropertyChanged」。這仍然沒有奏效。
感謝
太棒了...確實有效。有沒有更好的方法,我不知道?這不是一個糟糕的解決方案,但它使我做事情我做錯了什麼。我做出獨立財產的主要原因是能夠驗證它是在視圖模型中選擇的。再次感謝你的幫助。 – 2010-02-18 21:59:23
你的方法很好。像這樣實現IEquatable對於你的模型對象來說是個好習慣。您唯一的選擇是確保SelectedItem對象實例包含在ItemsSource集合中(引用相等)。這可能需要使用不同的方法來加載應用程序中的對象。 – 2010-02-18 22:58:26