为什么我不能将DataGrid SelectedItem绑定到用户控件内的DependencyProperty?

时间:2012-06-05 08:26:59

标签: wpf mvvm user-controls dependency-properties

我想将用户控件中的DataGrid SelectedItem绑定到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}"  />

并在viewmodel中:

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

并在视野中:

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

但它不起作用!!

2 个答案:

答案 0 :(得分:0)

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

 SelectedItem="{Binding ElementName=DataGridControl,

但是你是名为DataGridControl的用户控件吗?

<UserControl
  ...
  x:Name="DataGridControl">

答案 1 :(得分:0)

在Xaml中使用以下代码

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

在ViewModel中为所选项创建属性.Here Customer是具有Address,Name,OrderID等属性的类。

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

    }