[英]Silverlight user control databinding
我試圖創建一個包含列表框的用戶控件,但我不知道如何正確設置數據綁定。
在MainForm.xaml中(MyItems是在ViewModel中定義的ObservableCollection):
<my:ItemsList Items="{Binding MyItems}"/>
用戶控制:
public partial class ItemsList : UserControl
{
public ItemsList()
{
InitializeComponent();
}
public IEnumerable Items
{
get { return (IEnumerable)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(IEnumerable), typeof(ItemsList), null);
}
和xaml(省略了命名空間聲明):
<UserControl x:Class="MyApp.Controls.ItemsList">
<phone:LongListSelector ItemsSource="{Binding Items}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemName}" />
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</UserControl>
我得到的錯誤:BindingExpression路徑錯誤:在'MyApp.ViewModels.MainViewModel'上找不到'Items'屬性?
我所缺少的是在用戶控件的構造函數中為列表框設置數據上下文...
LayoutRoot.DataContext = this;
檢查:您是否使用頁面的正確DataContext(必須為ViewModel)?
用戶控制必須是:
public partial class ItemsList : UserControl
{
public ItemsList()
{
InitializeComponent();
}
public IEnumerable Items
{
get { return (IEnumerable)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(IEnumerable), typeof(ItemsList), new PropertyMetadata(ItemsChanged));
private static void ItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var controll = (ItemsList)d;
var val = (IEnumerable)e.NewValue;
controll.lls.ItemSource = val;
}
Xaml
<UserControl x:Class="MyApp.Controls.ItemsList">
<phone:LongListSelector x:name="lls">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemName}" />
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</UserControl>
希望它的幫助
在您的xaml中,您需要添加對viewmodel的引用,並使它成為控件的datacontext。
<UserControl xmlns:local="clr-namespace:"myproject.mynamespace;assembly=myproject">
<UserControl.Resources>
<local:myviewmodel x:key="viewModel"/>
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource viewModel}"/>
</UserControl.DataContext>
<phone:LongListSelector ItemsSource="{Binding Items}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ItemName}" />
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</UserControl>
請注意:可以使用DisplayMemberPath =“ ItemName”屬性而不是數據模板,除非您需要以某種方式與文本塊進行交互。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.