代码之家  ›  专栏  ›  技术社区  ›  Mark Cooper

来自代码的绑定行为

  •  2
  • Mark Cooper  · 技术社区  · 14 年前

    我使用的是自定义默认按钮附加行为(定义如下: 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); }
    
    ...
    }
    

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   AnthonyWJones    14 年前

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

    你有没有考虑过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
       }
     }
    

    我已经看完了你的其他问题和博客文章。必须将奇怪的属性附加到各种控件(如textbox)以实现默认按钮(最终与textbox无关)似乎是件坏事。

    更好的模式是在按钮上附加一个将被声明为默认值的属性(或者创建一个子类) Button 打电话 DefaultButton

    推荐文章