theSpyCry
theSpyCry

Reputation: 12283

How to read a Dependency property from a method

XAML:

<my:Control ItemsSource="{StaticResource MySource}"  A="true" />

Assume a Control with a dependency property A with a default value false; and a method to handle the Source Collection:

protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue) {}

in which you want to look at A and readout its value (which is true). how would you ensure, that A is already initialized and has a given value?

Or how should this be done correctly ?

In my case A is something like AllowLateBinding ..

Could coerce callback help me?

Upvotes: 0

Views: 72

Answers (2)

wpfwannabe
wpfwannabe

Reputation: 14867

I am not sure about the correctness but depending on your exact program logic, this might work:

protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
  if (IsInitialized)
  {
     DoWork(oldValue, newValue);
  }
  else
  {
    Initialized += (sender, e) => { DoWork(oldValue, newValue); };
  }
}

Upvotes: 1

Rune Grimstad
Rune Grimstad

Reputation: 36300

You could do this by either supplying a default value in the definition of the DependencyProperty or you could set the default value in your classes constructor.

When you register a dependency property you can specify a PropertyMetadata object that gives the default value.

Look at the DependencyProperty.Register method for instance.

Upvotes: 0

Related Questions