WPF Binding to my own property
I Created my own UserControl which has some a property which is calculated from something, lets call it Result. Now, I want to place this this control on a Grid and I have some buisness object. I want to bind a property in this object to my property Result. So I make something like this:
<MyControl Result="{Binding PropertyInO开发者_C百科bject}" ...
Of course DataContext is set and binding of other properties (wpf properties) is working. But this one is not. First it shoot an exception which says that I can't bind to non-dependency property. So I register it as one. Now it doesn't give exception but also doesn't get job done. So what do I do?
Without seeing your code and from the description of your problem, it sounds like your "Result" property is in the Code-Behind of your user control. If this is true, then you need to create "Result" as a dependency property. Then you can set your Result value in another method (Example is using SetResult())
Hope this helps. (There is a snippet for getting the shell of a dependency property into your code, in VS 2010, type "propdp" and then hit TAB twice.)
public int Result
{
get { return (int)GetValue(ResultProperty); }
set { SetValue(ResultProperty, value); }
}
// Using a DependencyProperty as the backing store for Result. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ResultProperty =
DependencyProperty.Register("Result", typeof(int), typeof(MyClassName), new UIPropertyMetadata(0));
private void SetResult()
{
int resultValue = 0;
// Do calculations
Result = 0;
}
The problem is probably that you assume that the binding is TwoWay by default, but it's not. When developing custom controls, you really need to think carefully when defining properties.
To define a property TwoWay by default (what you generally want), you need something like this:
public static readonly DependencyProperty PropProperty =
DependencyProperty.Register("Prop", typeof(Boolean), typeof(MyControl), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.**BindsTwoWayByDefault**));
精彩评论