views:

160

answers:

1

I'm trying real hard to make this short and easy to read. I am creating a custom control that has a DP defined (RandomNumber) in the code-behind. The value of this DP is set from a click event fired by a button in my control.

Here is the relevant code for this:

public partial class Tester 
{
    public int RandomNumber
    {
        get { return (int)GetValue(RandomNumberProperty); }
        set { SetValue(RandomNumberProperty, value); }
    }

    private Random rnd = new Random();
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        RandomNumber = rnd.Next();
    }

The click event works and the value is set and I can confirm that it is changed. The problem that I am having is when I use this control in my application and I try bind "RandomNumber" to another DP on my View Model the binding never updates:

 <DockPanel>
    <TextBlock Text="{Binding Path=Numeric}" 
               DockPanel.Dock="Top"
               Height="25"/>
    <TestProject:Tester RandomNumber="{Binding Path=Numeric}" 
                             DockPanel.Dock="Top"
                             Height="25"
                             x:Name="TestControl"/>

</DockPanel>

In the example above I have a view model with a DP named Numeric and I can confirm that this value is in fact never being updated by the binding.

I can't figure out what I'm doing wrong. Thanks in advance for any help!

+3  A: 

When you set RandomNumber in code, your binding is overwritten. This is generally true unless the binding is Mode=TwoWay or the RandomNumber has metadata BindsTwoWayByDefault.

Try making RandomNumber be BindsTwoWayByDefault:

  public static readonly DependencyProperty RandomNumberProperty =
    DependencyProperty.Register(
      "RandomNumber",
      typeof(int),
      typeof(Tester),
      new FrameworkPropertyMetadata
      {
        BindsTwoWayByDefault = true,
      });
Ray Burns
You're quick - You're accurate - You're... you're my heeero :)Thanks for the quick reply - this worked perfectly!
John