How to bind data user control inside listbox WP8(如何在列表框WP8中绑定数据用户控件)
问题描述
我有一个用户控件.它有一个 TextBlock.我想在里面绑定Text
I have a user control. It has a TextBlock. I want to bind Text in it
<UserControl x:Class="PhoneApp1.MyUserControl"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel Width="200" Height="200" Background="Red">
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
在 MyUserControls.xaml.cs
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(
"Text",
typeof(string),
typeof(MyUserControl),
new PropertyMetadata(null));
public string Text
{
get { return (string)GetValue(TextProperty); }
set
{
SetValue(TextProperty, value);
}
}
}
当我绑定到 ListBox 时,它无法正常工作
When I bind to ListBox it doesn't work correctly
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ListBox x:Name="mainListBox" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:MyUserControl Text="{Binding Text}" Margin="5"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
和 MainPage.xaml
and MainPage.xaml
public partial class MainPage : PhoneApplicationPage
{
ObservableCollection<User> list = new ObservableCollection<User>();
public MainPage()
{
InitializeComponent();
User user = new User("Thanh");
list.Add(user);
list.Add(new User("lfjlkgj"));
DataContext = list;
}
}
public class User
{
public string Text { get; set; }
public User(string name)
{
Text = name;
}
}
如何正确绑定到用户控件?谢谢!!!
How to bind to user controls correctly? Thanks!!!
推荐答案
从你的 UserControl Xaml 中删除这一行
Remove this line from your UserControl Xaml
DataContext="{Binding RelativeSource={RelativeSource Self}}"
控件的 xaml 中的绑定将正确绑定到定义的依赖项属性.你不需要做任何额外的事情.
Binding in the control's xaml will correctly bind to the defined dependency properties. You don't need to do anything extra.
如果您与用户控件中的其他数据源有名称冲突,您可以将 ElementName=UserControl 添加到您的绑定中.
If you have name conflicts with other data sources in your user control you can add ElementName=UserControl to your binding.
这篇关于如何在列表框WP8中绑定数据用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在列表框WP8中绑定数据用户控件
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
