![](/img/trans.png)
[英]Universal App XAML binding not working on UserControl when inside another UserControl
[英]Windows Universal UserControl Binding
我已經為Windows Universal應用程序創建了一個UserControl。
我的代碼背后有一個屬性,它定義為HourList文件,因此...
internal ObservableCollection<int> HourList =
new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
我想使用HourList將控件綁定到我的UserControl的xaml中,例如...
<ListView Width="100" ItemsSource="{Binding HourList, ElementName=timePicker}"
</ListView>
假設我已經這樣命名我的UserControl ...
<UserControl x:Name="timePicker"
但是,當我將控件放置在頁面上時,我的列表視圖沒有包含我所期望的小時列表。
我錯過了什么?
您只需在用戶控件的代碼背后創建一個屬性:
public ObservableCollection<int> HourList
{
get;
set;
}
public UserControl()
{
this.InitializeComponent();
HourList = new ObservableCollection<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 };
}
但是,在某些時候,如果您需要綁定到它或制作動畫,那么您將需要它成為如下所示的依賴項屬性:
public static readonly DependencyProperty HourListProperty =
DependencyProperty.Register("HourList",
typeof(ObservableCollection<int>), typeof(MyUserControl1),
new PropertyMetadata(new ObservableCollection<int>
{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21, 22, 23
}));
public ObservableCollection<int> HourList
{
get
{
return (ObservableCollection<int>)this.GetValue(HourListProperty);
}
set
{
this.SetValue(HourListProperty, value);
}
}
兩種方式的XAML都相同:
<StackPanel>
<UserControl x:Name="timePicker" />
<ListView
Height="100"
Foreground="Black"
Width="100"
ItemsSource="{Binding ElementName=timePicker, Path=HourList}">
</ListView>
</StackPanel>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.