【问题标题】:Bind a property to another property of a custom control将一个属性绑定到自定义控件的另一个属性
【发布时间】:2016-10-14 17:07:02
【问题描述】:

我正在制作基于按钮的自定义控件,并且我想将按钮的宽度绑定到类的属性。我查看了thisthisthis,但它们要么不是我想要的,要么不起作用。

Generic.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:CustomControl">

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}">
    <Setter Property = "Background" Value = "LightSalmon" />
    <Setter Property = "Foreground" Value = "Blue"/>
    <Setter Property = "Height" Value = "50"/>
    <Setter Property = "Width" Value = "{Binding MyCustomControl.TextBinding}"/>
    <Setter Property = "VerticalAlignment" Value = "Top"/>
    <Setter Property = "Margin" Value="10"/>
</Style>

</ResourceDictionary>

MyCustomControl.cs

namespace CustomControl
{
public class MyCustomControl : Button
{
    double m_textBinding = 50;
    public double TextBinding
    {
        get { return m_textBinding; }
        set { m_textBinding = value; }
    }
    static MyCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
            new FrameworkPropertyMetadata(typeof(MyCustomControl)));
    }
}
}

如果需要,我可以只使用“setter”函数,并手动指定"Width = value;",但我更喜欢使用绑定。目前"{Binding MyCustomControl.TextBinding}" 不起作用。

【问题讨论】:

  • TextBinding 似乎是一个定义控件宽度的属性的奇怪名称。
  • 是的,后来我意识到它是一个双精度,而不是字符串,我只是保留了这个名字,因为我很懒,这只是一个测试。

标签: c# wpf xaml binding


【解决方案1】:

这应该可行:

<Setter Property="Width"
        Value="{Binding TextBinding, RelativeSource={RelativeSource Self}}"/>

【讨论】:

  • 好吧,这有点奏效。它采用初始值 50 就好了,但如果我使用我的控件,那么在 MainWindow 代码隐藏中,如果我说 myControl.TextBinding = 100; 什么都不会发生
  • 这是因为您的住宿不会通知值更改。要么将其设为依赖属性,要么实现 INotifyPropertyChanged 接口。 UI 控件中最好使用依赖属性。
  • 啊,好的,谢谢。忘了我必须做那些。我做了一个 Dependency 属性,它工作得几乎完美。现在只需要让它的 fallbackvalue 就可以工作了。再次,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2010-11-14
  • 2012-03-24
  • 1970-01-01
  • 2015-06-29
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
相关资源
最近更新 更多