2012-10-31 26 views
0

我有一個簡單的行爲像傳遞一個字典的行爲

public class KeyBoardChangeBehavior : Behavior<UserControl> 
{ 
    public Dictionary<string, int> DataToCheckAgainst; 


    protected override void OnAttached() 
    { 
     AssociatedObject.KeyDown += _KeyBoardBehaviorKeyDown; 
    } 

    protected override void OnDetaching() 
    { 
     AssociatedObject.KeyDown -= _KeyBoardBehaviorKeyDown; 
    } 


     void _KeyBoardBehaviorKeyDown(object sender, KeyEventArgs e) 
    { 
     // My business will go there 
    } 

} 

我想ASIGN價值,這本詞典從視圖中,我把它叫做如下

<UserControl x:Class="newhope2.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:Interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
      xmlns:Behaviors="clr-namespace:newhope2" 
    mc:Ignorable="d" 
    d:DesignHeight="300" d:DesignWidth="400"> 

    <Interactivity:Interaction.Behaviors> 
     <Behaviors:KeyBoardChangeBehavior /> 
    </Interactivity:Interaction.Behaviors> 

    <Grid x:Name="LayoutRoot" Background="White"> 

    </Grid> 
</UserControl> 

卻怎麼也我將這本字典傳遞給XAML或其背後的代碼

回答

2

採取綁定,屬性必須是一個DependencyProperty

您需要定義屬性,在行爲,像這樣:

public Dictionary<string, int> DataToCheckAgainst 
    { 
     get { return (Dictionary<string, int>)GetValue(DataToCheckAgainstProperty); } 
     set { SetValue(DataToCheckAgainstProperty, value); } 
    } 

    public static readonly DependencyProperty DataToCheckAgainstProperty = 
     DependencyProperty.Register(
      "DataToCheckAgainst", 
      typeof(Dictionary<string, int>), 
      typeof(KeyBoardChangeBehavior), 
      new PropertyMetadata(null)); 

使用Visual Studio 「propdp」 片段。

用法是阿迪說,像這樣:

<Interactivity:Interaction.Behaviors> 
    <Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" /> 
</Interactivity:Interaction.Behaviors> 
+0

謝謝,如果我想以相同的方式傳遞文本框的文本 – AMH

+0

您需要添加字符串的另一個依賴項屬性,然後綁定到文本框綁定到的相同屬性,或者,如果文本框不綁定任何東西,使用ElementName綁定直接綁定到文本框。我建議閱讀關於綁定的文檔:http://msdn.microsoft.com/en-us/library/cc278072(v=vs.95).aspx –

+0

如何在XAML上定義此字典請 – AMH

1

您需要做的就是將字典聲明爲屬性,然後通過綁定將其傳遞給一個值。

在行爲:

public Dictionary<string, int> DataToCheckAgainst { get; set; } 

在XAML:

<Interactivity:Interaction.Behaviors> 
    <Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" /> 
</Interactivity:Interaction.Behaviors> 
+0

我忘了使用一個依賴屬性,而不是一個正常的財產的結合工作。鄧肯的解決方案就是要走的路。 –

+0

謝謝,如果我想以相同的方式通過文本框的文本 – AMH

+0

我不確定你指的是什麼文本框,但是你可以改變綁定,使其綁定到文本框(通過使用ElementName或RelativeSource)。 –

相關問題