定义一个UserControl控件,将里面的值进行绑定
<UserControl x:Class="CeShiMvvmDeTest.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CeShiMvvmDeTest"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<StackPanel Background="White">
// 着重注意这句话
<TextBlock Text="{Binding Id,RelativeSource={RelativeSource AncestorType=UserControl}}" FontSize="60"/>
</StackPanel>
</UserControl>
这个UserControl还需要进入后端,设置依赖属性Id
public partial class Test : UserControl
{
public Test()
{
InitializeComponent();
}
// 猜想1:添加依赖属性,通过依赖属性绑定到Test后台代码
// 定义依赖属性Id
public int Id
{
get { return (int)GetValue(IdProperty); }
set { SetValue(IdProperty, value); }
}
public static readonly DependencyProperty IdProperty =
DependencyProperty.Register("Id", typeof(int), typeof(Test), new PropertyMetadata(null));
MainView里面引用
<StackPanel Grid.Row="1">
<local:Test Id="456"/>
<local:Test Id="123"/>
</StackPanel>