0

I am making a custom control based on a button, and I want to bind the width of the button to a property of the class. I have looked at this, this, and this, but they either aren't what I'm looking for, or don't work.

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)));
    }
}
}

If need be, I can just use the "setter" function, and specify manually, "Width = value;", but I would prefer to use a binding. Currently the "{Binding MyCustomControl.TextBinding}" isn't working.

Community
  • 1
  • 1
  • `TextBinding` seems to be a strange name for a property that defines the width of a control. – Clemens Oct 14 '16 at 17:15
  • Ya, I realized after that it is a double, not string, and I just kept the name cause I'm lazy, and this is just a test. –  Oct 14 '16 at 17:16

1 Answers1

1

This should work:

<Setter Property="Width"
        Value="{Binding TextBinding, RelativeSource={RelativeSource Self}}"/>
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Ok, that kinda worked. It takes the initial value of 50 just fine, but if I use my control, then in the MainWindow codebehind, if I say `myControl.TextBinding = 100;` nothing happens –  Oct 14 '16 at 17:22
  • That is because your property doesn't notify about a value change. Either you make it a dependency property or you implement the INotifyPropertyChanged interface. Dependency property would be preferrable in a UI control. – Clemens Oct 14 '16 at 17:25
  • Ah, right, thank you. Forgot I had to do those. I made a Dependency property and it is working almost perfectly. Just need to get its fallbackvalue to work now. Again, thank you so much! –  Oct 14 '16 at 17:40