Binding Attached Behaviour from code
I am using a custom default button attached behaviour (as defined here: Silverlight 4 Default Button Service).
I am able to bind this successfully in XAML, but in a nested user control, in code behind the following does not work:
public partial class MyNestedUserContol{
/// a DP for storing the name of the default button, used in the ElementName binding
public string DefaultButton {
get { return (string)GetValue(DefaultButtonProperty); }
set { SetValue(DefaultButtonProperty, value); }
}
public static readonly DependencyProperty DefaultButtonProperty =
DependencyProperty.Register("DefaultButton", typeof(string), typeof(TeamReferenceFieldEditor), new PropertyMetadata(null));
开发者_开发百科...
private void CreateCustomControls(){
...
TextBox tb = new TextBox();
...
AddDefaultButtonBinding(tb);
...
}
private void AddDefaultButtonBinding(Control control) {
Binding binding = new Binding();
binding.ElementName = this.DefaultButton;
control.SetBinding(DefaultButtonService.DefaultButtonProperty, binding); }
...
}
How should I create the binding for this in code?
Thanks, MarkUltimately this will be a problem in namescopes. The value assigned to ElementName probably doesn't exist in the same namescope that the TextBox belongs to.
Have you considered simply using:-
private void MainPage_Load(object sender, RoutedEventArgs e)
{
LayoutRoot.AddHandler(UIElement.KeyUpEvent, LayoutRoot_KeyUp, true)
}
private void LayoutRoot_Keyup(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// invoke default operation here
}
}
I've read through your other question and the blog article. Its seems like a bad smell to have to attach strange properties to various controls like a textbox to implement a default button, which ultimately has nothing to do with the textbox.
It would be a better pattern to attach a property on the button which is to be declared the default (or to create a sub-class of Button
called DefaultButton
) and to have that co-operate with the containing UserControl, Page or ChildWindow to watch for the enter key. This would not then have to involve other controls not directly related to delivering this functionality.
精彩评论