将自定义控件上的新属性绑定到视图模型

发布于 2024-07-27 04:43:45 字数 748 浏览 1 评论 0原文

如何扩展现有控件(在我的情况下为 ComboBox)以包含可以绑定到视图模型上的属性的新属性?

我在控件的类上有一个依赖属性,如下所示:

public class MyComboBox : ComboBox
{
    public static readonly DependencyProperty MyTextProperty =
        DependencyProperty.Register("MyText", typeof(string), typeof(MyComboBox));

    public string MyText
    {
        get
        {
            return GetValue(MyComboBox.MyTextProperty).ToString();
        }

        set
        {
            SetValue(MyComboBox.MyTextProperty, value);             
        }
    }

并且想要从 XAML 中以声明方式绑定到它,如下所示:

<MyComboBox MyText="{Binding MyTextOnViewModel,
    UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>  

绑定不起作用,有什么想法为什么吗?

谢谢。

How do i extend an existing control (ComboBox in my case) to include a new property which i can bind to a property on my view model??

I have a Dependancy Property on the control's class as follows:

public class MyComboBox : ComboBox
{
    public static readonly DependencyProperty MyTextProperty =
        DependencyProperty.Register("MyText", typeof(string), typeof(MyComboBox));

    public string MyText
    {
        get
        {
            return GetValue(MyComboBox.MyTextProperty).ToString();
        }

        set
        {
            SetValue(MyComboBox.MyTextProperty, value);             
        }
    }

And want to bind to it declaratively from XAML like this:

<MyComboBox MyText="{Binding MyTextOnViewModel,
    UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>  

The Binding just won't work, any ideas why??

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我一直都在从未离去 2024-08-03 04:43:45

当属性声明为 MyTextProperty 时,您的 getter 和 setter 引用 TestTextProperty。

您的吸气剂也应该进行强制转换而不是调用 .ToString()

return (string)GetValue(MyTextProperty);

请参阅此页面 获取更完整的说明。

Your getter and setter reference TestTextProperty while the property is declared as MyTextProperty.

Your getter should also be casting instead of calling .ToString()

return (string)GetValue(MyTextProperty);

See this page for more complete instructions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文