简体   繁体   English

WPF中的Datagrid SelectedItem绑定

[英]Datagrid SelectedItem binding in WPF

I am trying to get the SelectedItem of a DataGrid but whenever i add the "SelectedItem.." that is commented out, my window does not show when i run the application. 我正在尝试获取DataGridSelectedItem ,但是每当我添加注释掉的“ SelectedItem ..”时,运行应用程序时窗口都不会显示。 Is there something wrong with the binding? 绑定有问题吗?

        <StackPanel Grid.Column="2" Margin="40">
            <Label Content="Customer Table"/>
            <DataGrid Name="dgCustomer" 
                      AutoGenerateColumns="False" 
                      ItemsSource="{Binding Path=CustomerDataCollection}" 
                      IsReadOnly="True" 
                      TargetUpdated="dg_TargetUpdated"
                      SelectionMode="Single"
                      SelectionUnit="FullRow">
                <!--SelectedItem="{Binding Path=CustomerItemSelected, Mode=OneWayToSource}"-->
                <DataGrid.Columns>
                    <DataGridTextColumn Width="Auto" Header="ID" Binding="{Binding Id, NotifyOnTargetUpdated=True}"/>
                    <DataGridTextColumn Width="*" Header="Description" Binding="{Binding Description}"/>
                    <DataGridTextColumn Width="Auto" Header="OrderID" Binding="{Binding OrderID, NotifyOnTargetUpdated=True}"/>
                </DataGrid.Columns>
            </DataGrid>
        </StackPanel>

and I am using ObservableCollection 我正在使用ObservableCollection

    private ObservableCollection<Customer> m_CustomerDataCollection = new ObservableCollection<Customer>();
    public ObservableCollection<CustomerAlcove> CustomerDataCollection
    {
        get => m_CustomerDataCollection;
        private set => Set(ref m_CustomerDataCollection, value);
    }

    private Customer m_CustomerItemSelected = new Customer();
    public Customer CustomerItemSelected
    {
        get => m_CustomerItemSelected;
        private set => Set(ref m_CustomerItemSelected, value);
    }

You are binding to a readonly property (CustomerItemSelected has a private setter) with a OneWayToSource Binding. 您正在使用OneWayToSource绑定绑定到只读属性(CustomerItemSelected具有私有设置程序)。 This will not work, so make your setter public: 这将不起作用,因此请向您的二传手公开:

public Customer CustomerItemSelected
{
    get => m_CustomerItemSelected;
    set => Set(ref m_CustomerItemSelected, value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM