Usercontrol 不同的控件属性访问

Usercontrol different controls properties access

我创建了我的第一个 WPF MVVM 模式解决方案。我创建了一个 UserControl,我想在我的 MainWindow 中重用这个控件,因为样式是相同的,唯一不同的是这两个控件是数据源。第一个控件使用 ObervableCollection 索引 0,第二个 UserControl 使用相同的 OberservableCollection 索引 1。observablecollection 在我的 Mainviewmodel 中,如果我在我的 UserControl 内部进行绑定,则绑定工作正常。

不想像这样将 UserControl 内部绑定到我的模型:

用户控件:

   <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="PersonModel.FirstName"></TextBlock>
        <TextBlock Grid.Row="1" Text="PersonModel.FirstName"></TextBlock>
    </Grid>

我想在我的主窗口中绑定我的用户控件的每个嵌套控件。

MainWindow.xaml

<desktop:UserControl1 Textblock1.Text="{Binding PersonModel.FirstName} TextBlock2.Text="{Binding PersonModel.LastName}"></desktop:UserControl1>

很容易将任何可绑定公开为UserControl依赖属性,这里是CustomText一个:

public partial class UserControl1 : UserControl
{
    public string CustomText
    {
        get { return (string)GetValue(CustomTextProperty); }
        set { SetValue(CustomTextProperty, value); }
    }
    public static readonly DependencyProperty CustomTextProperty =
        DependencyProperty.Register("CustomText", typeof(string), typeof(UserControl1), new PropertyMetadata());

    public UserControl1()
    {
        InitializeComponent();
        DataContext = this;
    }
}

在xaml中你绑定到它:

<UserControl ... >
    <TextBlock Text="{Binding CustomText}"  />
</UserControl>

用法为:

<local:UserControl1 CustomText="{Binding SomeProperty" />

另一种方法是使用依赖回调 属性,这样你可以在 UserControl 的代码后面更改很多东西,例如开始动画。

我不知道是否有办法公开 UserControl 的完整子控件,但也许您不需要它(而是创建一些专用的依赖属性来更改特定的 属性具体控制)。


另一种可能性是给UserControl一个名字,并在window的代码后面使用它。在这种情况下,您可以通过给它们命名(x:Name)并使用属性来公开 UserControl 控件:

public partial class UserControl1 : UserControl
{
    public TextBlock TextBlock => textBlock; // textBlock is x:Name
    ...
}

现在您可以 bind in code 例如userControl1.TextBlock.Visibility(其中 userControl1<local:UserControl1 />x:Name)。