首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字典传递给行为

将字典传递给行为
EN

Stack Overflow用户
提问于 2012-11-01 05:05:00
回答 2查看 327关注 0票数 0

我有一个这样的简单行为

代码语言:javascript
复制
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 
    }

}

我想从视图中为这个字典赋值,我这样调用它

代码语言:javascript
复制
<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的行为或它背后的代码

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-01 09:04:15

要获取绑定,属性必须是DependencyProperty

您需要在行为中定义属性,如下所示:

代码语言:javascript
复制
    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“代码段。

用法如Adi所说,如下所示:

代码语言:javascript
复制
<Interactivity:Interaction.Behaviors>
    <Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" />
</Interactivity:Interaction.Behaviors>
票数 3
EN

Stack Overflow用户

发布于 2012-11-01 05:31:08

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

在行为中:

代码语言:javascript
复制
public Dictionary<string, int> DataToCheckAgainst { get; set; }

在XAML中:

代码语言:javascript
复制
<Interactivity:Interaction.Behaviors>
    <Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" />
</Interactivity:Interaction.Behaviors>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13167411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档