绑定ListView SelectedItem列MVVM

时间:2018-03-20 04:37:20

标签: c# wpf xaml listview selecteditem

我有以下XAML

<ListView ItemsSource="{Binding Franchises, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedFranchise, Mode=TwoWay}" SelectionMode="Single" Height="150">
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="FranchiseID" Header="ID" DisplayMemberBinding="{Binding FranchiseID}"/>
            <GridViewColumn Header="Franchise Name" DisplayMemberBinding="{Binding FranchiseName}"/>
        </GridView>
    </ListView.View>
</ListView>

我想将FranchiseID传递给我的Presenter视图模型SelectedFranchise值。

Presenter ViewModel

public class Presenter : ObservableObject
{

    private DataView _Franchises = Controller.BaseballDB.Tables["Franchise"].DefaultView;
    private long _SelectedFranchise;

    public DataView Franchises
    {
        get
        {
            Controller.Refresh();
            _Franchises = Controller.BaseballDB.Tables["Franchise"].DefaultView;
            return _Franchises;
        }
        set
        {
            Controller.Refresh();
            _Franchises = Controller.BaseballDB.Tables["Franchise"].DefaultView;
            RaisePropertyChangeEvent("Franchises");
        }
    }

    public long SelectedFranchise
    {
        get { return _SelectedFranchise; }
        set
        {
            _SelectedFranchise = value;
            Debug.Print(_SelectedFranchise.ToString());
        }
    }
}

现在它给了我一个错误,因为它想要将所选项的整个字符串传递给属性。我在网上搜索过,但显然每个人都只想选择一个项目,只有一列。

1 个答案:

答案 0 :(得分:1)

SelectedValuePathSelectedValue一起使用。请确保FranchiseIDSelectedFranchise的数据类型相同。

<ListView ItemsSource="{Binding Franchises, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="FranchiseID" SelectedValue="{Binding SelectedFranchise}" SelectionMode="Single" Height="150">
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="FranchiseID" Header="ID" DisplayMemberBinding="{Binding FranchiseID}"/>
            <GridViewColumn Header="Franchise Name" DisplayMemberBinding="{Binding FranchiseName}"/>
        </GridView>
    </ListView.View>
</ListView>