问题描述
我正在尝试在ItemsRepeater中使用UserControl并遇到问题。我正在使用Prism和MVVM模型
我在单独的A.xaml文件中定义了一个UserControl
<UserControl>
<Grid>
<Button Background="Grey" Content="{x:Bind Aviewmodel.text}">
<Button>
<Grid>
<UserControl>
相应的A.xaml.cs文件具有对定义属性文本的Aviewmodel的绑定
<Grid>
<ItemsRepeater ItemSource={"x:Bind Bviewmodel.listofObservableCollection"}>
<ItemRepeater.Layout>
<StackLayout>
</StackLayout>
</ItemRepeater.Layout>
</ItemsRepeater>
</Grid>
此XAML文件具有对应的B.XAML.cs文件,该文件绑定到具有“可观察的列表”集合的Bviewmodel。我希望显示一个垂直按钮列表,该按钮包含使用UserControl的“观察集合列表”中的文本。我该如何实现?
解决方法
如何在UWP的ItemsRepeater中使用用户控件
您可以将UserControl插入ItemsRepeater的ItemTemplate
中。并给UserControl DependencyProperty接收文本值。请注意,您需要像以下内容一样将ListOfObservableCollection
的内容编辑为AViewModel
UserControl
<UserControl>
<Grid>
<Button Background="Gray" Content="{Binding ButtonContent}" />
</Grid>
</UserControl>
-
后面的代码
public sealed partial class AControl : UserControl { public AControl() { this.InitializeComponent(); (this.Content as FrameworkElement).DataContext = this; } public string ButtonContent { get { return (string)GetValue(ButtonContentProperty); } set { SetValue(ButtonContentProperty,value); } } // Using a DependencyProperty as the backing store for ButtonContent. This enables animation,styling,binding,etc... public static readonly DependencyProperty ButtonContentProperty = DependencyProperty.Register("ButtonContent",typeof(string),typeof(AControl),new PropertyMetadata(null)); }
用法
<Page.DataContext>
<local:BViewModel x:Name="ViewModel" />
</Page.DataContext>
<Grid>
<muxc:ItemsRepeater ItemsSource="{Binding ListOfObservableCollection}">
<muxc:ItemsRepeater.ItemTemplate>
<DataTemplate>
<local:AControl ButtonContent="{Binding Text}" />
</DataTemplate>
</muxc:ItemsRepeater.ItemTemplate>
</muxc:ItemsRepeater>
<local:AControl ButtonContent="hh" />
</Grid>
背后的代码
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
public class AViewModel
{
public string Text { get; set; }
}
public class BViewModel
{
public ObservableCollection<AViewModel> ListOfObservableCollection { get; set; }
public BViewModel()
{
ListOfObservableCollection = new ObservableCollection<AViewModel>();
ListOfObservableCollection.Add(new AViewModel { Text = "Test1" });
ListOfObservableCollection.Add(new AViewModel { Text = "Test1" });
ListOfObservableCollection.Add(new AViewModel { Text = "Test1" });
ListOfObservableCollection.Add(new AViewModel { Text = "Test1" });
}
}