【问题标题】:How to bind a property from my usercontrol content control to a property in my viewmodel?如何将我的用户控件内容控件中的属性绑定到我的视图模型中的属性?
【发布时间】:2011-10-31 12:05: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>

我想在诸如 MainWindowView 之类的视图中使用此控件 如何将 Ytextbox 文本属性绑定到 MainWindowViewModel 中的属性?

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

我知道我必须为我的控件定义一个DependencyProperty,直到我可以将我的视图模型中的一个属性绑定到它,所以我为我的控件定义一个依赖属性,如下所示:

public static readonly DependencyProperty InfoTextProperty = 
        DependencyProperty.Register("InfoText", typeof(string), typeof(customtextbox), new FrameworkPropertyMetadata(false));

public string InfoText
{
    get { return (string)GetValue(InfoTextProperty);}
    set
    {
        SetValue(InfoTextProperty, value); 
    }
} 

当我为控件定义依赖属性时,出现 xaml 错误:

错误 1 ​​无法创建“customtextbox”的实例。

【问题讨论】:

    标签: c# wpf xaml mvvm user-controls


    【解决方案1】:
    new FrameworkPropertyMetadata(false)
    

    您不能将string 属性的默认值设置为false(当然是bool)。

    可能还有一些其他问题(例如,您在用户控制声明中对 TextBox 没有绑定,并且您尝试设置一个您没有在创建实例的位置注册的属性)但是对于那些您应该搜索的问题。

    【讨论】:

      【解决方案2】:

      您正在尝试将布尔值设置为字符串 DependencyProperty。应该是这样的

       new FrameworkPropertyMetadata(string.Empty)
      

      new FrameworkPropertyMetadata(null)
      

      【讨论】:

        【解决方案3】:

        嗯,试试这个作为你的依赖属性的代码。

        public static readonly DependencyProperty InfoTextProperty = 
            DependencyProperty.Register(
                "InfoText",
                typeof(string),
                typeof(customtextbox)
            );
        
            public string InfoText
            {
        
                get { return (string)GetValue(InfoTextProperty);}
                set {SetValue(InfoTextProperty, value); }
            } 
        

        我刚刚从您注册属性时删除了最后一个参数,我认为这应该为属性提供默认值,而您提供的是布尔值而不是字符串,无论如何它是一个可选参数。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-09
          • 1970-01-01
          • 2013-01-12
          • 1970-01-01
          相关资源
          最近更新 更多