简体   繁体   中英

Custom WPF Control Dependency Property Not Binding to external DP

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM