2010-08-09 39 views
2

我正在使用自定義默認按鈕附加行爲(如此處定義: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); } 

... 
} 

我應該如何在代碼中創建這種情況的結合?
謝謝,
馬克

回答

0

最終這將是一個在名望範疇的問題。分配給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 
    } 
} 

我已經通過您的其他問題和博客文章閱讀。它似乎是一種難聞的氣味,必須附加奇怪的屬性,像文本框這樣的各種控件來實現默認按鈕,最終與文本框無關。

將一個屬性添加到要聲明爲默認按鈕的按鈕(或創建名爲DefaultButton的子類Button)並且與包含的UserControl,Page共同操作將會是更好的模式或ChildWindow來監視回車鍵。這樣就不需要涉及與提供此功能沒有直接關係的其他控件。