【问题标题】:Binding Attached Behaviour from code从代码绑定附加行为
【发布时间】:2010-08-09 14:16:30
【问题描述】:

我正在使用自定义默认按钮附加行为(定义如下:Silverlight 4 Default Button Service)。

我能够在 XAML 中成功绑定它,但在嵌套用户控件中,下面的代码不起作用:

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

...
}

我应该如何在代码中为此创建绑定?
谢谢,
标记

【问题讨论】:

    标签: binding silverlight-3.0 attachedbehaviors


    【解决方案1】:

    这最终将成为名称范围的问题。分配给 ElementName 的值可能不存在于 TextBox 所属的同一个名称范围内。

    您是否考虑过简单地使用:-

     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
       }
     }
    

    我已阅读您的其他问题和博客文章。必须将奇怪的属性附加到各种控件(如文本框)以实现默认按钮,这似乎是一种难闻的气味,最终与文本框无关。

    在要声明为默认值的按钮上附加一个属性(或创建一个名为DefaultButtonButton 的子类)并与包含UserControl、Page 或 ChildWindow 来监视回车键。这样就不必涉及与提供此功能没有直接关系的其他控件。

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2017-01-25
      • 2013-09-17
      • 2011-03-03
      • 2023-03-07
      • 2012-05-12
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多