【问题标题】:How to bind a property from my usercontrol content control to a property?如何将我的用户控件内容控件中的属性绑定到属性?
【发布时间】:2011-11-02 13:43:22
【问题描述】:

我有一个这样的用户控件:

<UserControl x:Class="MySample.customtextbox"
         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" 
         mc:Ignorable="d" 
         d:DesignHeight="20" d:DesignWidth="300">
<Grid>
       <TextBox x:Name="Ytextbox"  Background="Yellow"/> 
</Grid>
 </UserControl>

我想在 mvvm 模式中使用我的控件...我希望我可以将我的视图模型中的属性绑定到 Ytextbox 文本属性

<CT:customtextbox  ?(Ytextbox)Text ="{binding  mypropertyinviewmodel}"/>

...我该怎么做?

【问题讨论】:

    标签: c# wpf mvvm user-controls


    【解决方案1】:

    您应该在 UserControl 上创建一个属性并将其内部绑定到 TextBox 的文本。

    <UserControl Name="control" ...>
        <!-- ... -->
            <TextBox Text="{Binding Text, ElementName=control}"
                     Background="Yellow"/>
    
    public class customtextbox : UserControl
    {
        public static readonly DependencyProperty TextProperty =
            TextBox.TextProperty.AddOwner(typeof(customtextbox));
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }
    }
    

    用法:

    <CT:customtextbox Text="{Binding  mypropertyinviewmodel}"/>
    

    (不要将 UserControl 中的 DataContext 设置为自身,除非您希望所有期望继承 DataContext 的外部绑定都失败,请使用 ElementNameRelativeSource 进行内部绑定)

    【讨论】:

    • 我有点困惑,因为 TextBox 属性名称和自定义控件属性是相同的,我打算使用不同的属性名称,但在我意识到要更改它之后它起作用了 :) +1 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多