我有一個用戶控件,它有一個網格,並顯示一個人的列表,當我點擊在我的網格中的行時,我得到了獲取選定的行項目在我的視圖model.my問題是,我不能得到選定的行在我的usercontrol中我view3model SelectedPersonModel。在這裏的,我正在使用的代碼: 我的用戶XAML代碼和代碼背後:如何設置/從usercontrol的依賴項屬性獲取值?
<Grid>
<DataGrid ItemsSource="{Binding PersonList,Mode=TwoWay,RelativeSource={RelativeSource AncestorType={x:Type Control:UcPersonList}}}" SelectedItem="{Binding SelectedRow,RelativeSource={RelativeSource AncestorType={x:Type Control:UcPersonList}}}"/>
</Grid>
public partial class UcPersonList : UserControl
{
public UcPersonList()
{
InitializeComponent();
this.DataContext = this;
}
#region PersonListProperty
public static readonly DependencyProperty PersonListProperty =
DependencyProperty.Register("PersonList", typeof(BindingList<PersonModel>), typeof(UcPersonList),
new FrameworkPropertyMetadata
{
DefaultValue = new BindingList<PersonModel>(),
BindsTwoWayByDefault = true
});
public BindingList<PersonModel> PersonList
{
get { return (BindingList<PersonModel>)GetValue(PersonListProperty); }
set
{
SetValue(PersonListProperty, value);
}
}
#endregion
#region SelectedPerson
public static readonly DependencyProperty SelectedRowProperty =
DependencyProperty.Register("SelectedRow", typeof(PersonModel), typeof(UcPersonList),
new FrameworkPropertyMetadata
{
DefaultValue = new PersonModel(),
BindsTwoWayByDefault = true
});
public PersonModel SelectedRow
{
get { return (PersonModel)GetValue(SelectedRowProperty); }
set
{
SetValue(SelectedRowProperty , value);
}
}
#endregion
}
在我看來,我有:
<my:UcPersonList x:Name="uclist" Grid.Row="2" PersonList="{Binding Path=PersonList,Mode=TwoWay}" SelectedRow="{Binding Path=SelectedPersonModel ,Mode=TwoWay}" />
我的視圖模型:
public MainViewModel()
{
SelectedPersonModel = new PersonModel();
PersonList = new BindingList<PersonModel>();
PersonList.Add(new PersonModel { FirstName = "A", LastName = "AA", Age = 19 });
PersonList.Add(new PersonModel { FirstName = "B", LastName = "BB", Age = 25 });
PersonList.Add(new PersonModel { FirstName = "C", LastName = "CC", Age = 30 });
}
public BindingList<PersonModel> PersonList { get; set; }
public PersonModel SelectedPersonModel{get;set;}
我想那將用戶控制PersonList從我的視圖模型和視圖模型中SelectedPersonModel property.how得到selectedRow 屬性值做呢?
我必須在哪裏設置DataContext? –
我說「不要」不是「把它放在別處」。 –
@HB雖然我同意你的看法,但你的回答並沒有回答 – Rachel