0

我想将DataGrid SelectedItem用户控件内部的a绑定到a DependencyProperty ,这是我的代码:

在用户控件(DataGridControl)中:

        public static readonly DependencyProperty DataGridSelectedItemProperty
        = DependencyProperty.Register(
        "DataGridSelectedItem"
        , typeof(object)
        , typeof(DataGridSelectorControl)
        , new UIPropertyMetadata(null));

    public object DataGridSelectedItem
    {
        get { return (object)GetValue(DataGridSelectedItemProperty); }
        set { SetValue(DataGridSelectedItemProperty, value); }
    }

  <DataGrid ItemsSource="{Binding Source={StaticResource theSource}}" 
           SelectedItem="{Binding ElementName=DataGridControl,Path=DataGridSelectedItem,UpdateSourceTrigger=PropertyChanged}"  />

在视图模型中:

    object projectSelectedItem;
    public object ProjectSelectedItem
    {
        get
        {
            return projectSelectedItem;
        }
        set
        {
            projectSelectedItem = value;
            RaisePropertyChanged("ProjectSelectedItem");
        }
    }

并认为:

<MvvmCommonControl:DataGridControl  DataGridSelectedItem="{Binding ProjectSelectedItem}"  DataGridDataCollection="{Binding DataCollection}"/>

但它不起作用!

4

2 回答 2

0

在 Xaml 中使用下面的代码

<DataGrid ItemsSource="{Binding Path=Person,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False"   SelectedItem="{Binding Path=SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

在 ViewModel 中,为选定的项目创建属性。这里的客户是具有地址、名称、订单 ID 等属性的类。

private Customer selectedItem = new Customer();

        public Customer SelectedItem
        {

            get
            { return selectedItem; }
            set
            {
                selectedItem = value;
                InvokePropertyChanged("SelectedItem");
             }                 
        }

创建一个类来定义依赖属性

class DataGridSelectedItemBehaviour:DependencyObject
    {
        public static readonly DependencyProperty SelectedItemProperty
        = DependencyProperty.Register(
        "SelectedItem"
        , typeof(object)
        , typeof(CustomerViewModel)
        , new UIPropertyMetadata(null));

        public object SelectedItem
        {
            get { return (object)GetValue(SelectedItemProperty); }
            set { SetValue(SelectedItemProperty, value); }
        }

    }
于 2014-05-28T09:00:59.077 回答
0

您的用户控件中有以下内容:

 SelectedItem="{Binding ElementName=DataGridControl,

但是您的用户控件是否已命名DataGridControl

<UserControl
  ...
  x:Name="DataGridControl">
于 2012-06-05T11:03:29.520 回答