当property = true时,将ListviewItem设置为selected

时间:2016-08-04 08:00:44

标签: c# wpf

我有一个Listview。

XAML:

<ListView Name="lv_records" SelectionMode="Multiple" SelectionChanged="lv_records_SelectionChanged" />

我使用一个简单的类将此Listview的Itemssource设置为List。

类别:

public class Container
{
    public string Database { get; set; }
    public string Value { get; set; }
    public bool Selected { get; set; }

    public Container(string db, string val)
    {
        Database = db;
        Value = val;
        Selected = false;    
    }
}

lv_records.ItemsSource = ContainerList

但我想根据bool值选择元素。 这怎么可能? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

IsSelected中绑定ListViewItem的ItemContainerStyle属性:

<ListView ...>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="IsSelected" Value="{Binding Selected}"/>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

为了通知Selected属性的更改,Container类必须实现INotifyPropertyChanged接口:

public class Container : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool selected;
    public bool Selected
    {
        get { return selected; }
        set
        {
            selected = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Selected"));
        }
    }

    ...
}