c# - Usercontrol不同控件属性访问

标签 c# wpf xaml mvvm user-controls

我创建了我的第一个 WPF MVVM 模式解决方案。我创建了一个 UserControl,我想在我的 MainWindow 中重用这个控件,因为样式是相同的,这两个控件之间的唯一区别是数据源。第一个控件使用 ObervableCollection 索引 0,第二个 UserControl 使用来自同一个 OberservableCollection 索引 1。observablecollection 在我的 Mainviewmodel 中,并且如果我在 UserControl 内部进行绑定(bind),则绑定(bind)效果很好。

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

用户控制:

   <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 中绑定(bind)我的 Usercontrol 的每个嵌套控件。

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

最佳答案

很容易将任何可绑定(bind)的内容暴露为 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 中,您绑定(bind)到它:
<UserControl ... >
    <TextBlock Text="{Binding CustomText}"  />
</UserControl>

用法将是:
<local:UserControl1 CustomText="{Binding SomeProperty" />

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

不知道有没有办法完全暴露UserControl的子控件,但也许您不需要它(而是创建一些专用的依赖属性来更改特定控件的特定属性)。

另一种可能性是给 UserControl一个名称并在窗口后面的代码中使用它。在这种情况下,您可以公开 UserControl通过给它们命名( x:Name )并使用属性来控制:
public partial class UserControl1 : UserControl
{
    public TextBlock TextBlock => textBlock; // textBlock is x:Name
    ...
}

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

关于c# - Usercontrol不同控件属性访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39125753/

相关文章:

c# - DataGrid -- AlternatingRowBackground 颜色干扰 "IsMouseOver"颜色

c# - 打开/关闭闪光灯

c# - 加速 40,000 行的 linq 查询

c# - 用完整的字符串分隔符拆分字符串

c# - 扩展头删除 "_"字符

c# - 如何使用 ReactiveCommand?

c# - C# 中的电子邮件调度 (ASP .NET)

c# - 硬代码 Entity Framework 连接字符串

c# - 如何将用户控件内容控件中的属性绑定(bind)到属性?

c# - ListView 拖放时未更新