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 
    }

}

我想从视图中为这个字典赋值,我称之为如下

<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 或其背后代码的行为

4

2 回答 2

3

要采用 Binding,属性必须是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>
于 2012-11-01T01:04:15.080 回答
1

您需要做的就是将字典声明为属性,然后通过绑定将值传递给它。

在行为中:

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

在 XAML 中:

<Interactivity:Interaction.Behaviors>
    <Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" />
</Interactivity:Interaction.Behaviors>
于 2012-10-31T21:31:07.750 回答