WPF ListView 设置 SelectedItem

发布于 2024-08-22 06:10:39 字数 3487 浏览 11 评论 0原文

我试图寻找这个问题的答案,但我没有任何运气。基本上我有一个列表视图,它绑定到从视图模型返回的集合。我将列表视图的选定项目绑定到列表视图中的属性,以便执行验证以确保选择项目。问题是有时我想加载此列表视图与已选择的项目之一。我希望能够使用我想要选择的对象在我的视图模型上设置属性,并让它自动选择该项目。这并没有发生。我的列表视图加载时未选择任何项目。我可以成功地将所选索引设置为第 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"。那还是不行。

谢谢

I've tried to search for an answer to this but I'm not having any luck. Basically I have a listview that is bound to a collection returned from a view model. I bind the selected item of the list view to a property in my listview in order to perform validation to ensure that an item is selected. The problem is that sometimes I want to load this listview with one of the items already selected. I was hoping to be able to set the property on my view model with the object I want selected and have it automatically select that item. This is not happening. My listview loads without an item selected. I can successfully set the selected index to the 0th index so why shouldn't I be able to set the selected value. The list view is in single selection mode.

Here's the pertinent code from my list view

<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>

And here is the pertinent code from my view model

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);
        }
    }

}

I should note that the "Style" referenced here has nothign to do with WPF. It's a business object. I'm really looking for a solution that doesn't break the MVVM pattern, but I'd be willing to just get something functioning. I've attempted to loop through the Listview.Items list just to set it manually but it's always empty when I try. Any help is appreciated.

Edit: I updated the code to use INotifyPropertyChanged. It's still not working. Any other suggestions
2nd Edit: I added UpdateSourceTrigger="PropertyChanged". That still did not work.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江湖正好 2024-08-29 06:10:39

您的问题很可能是由于您的 SelectedItem StyleAvailableStyles 中的匹配实例不同的 Style 实例引起的在 ItemsSource 中。

您需要做的是在 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);
    }
}

Your problem is most likely caused because your SelectedItem Style is a different Style instance than the matching one in the AvailableStyles in the ItemsSource.

What you need to do is provide your specific definition of equality in your Style class:

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);
    }
}
青朷 2024-08-29 06:10:39

Hmm... it looks like you forgot to implement INotifyPropertyChanged for the SelectedStyle property...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文