Passing a dictionary to a behavior
-
24-07-2021 - |
Question
I have a simple Behavior like that
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
}
}
I want to asign value to this dictionary from the view , I call it as following
<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>
but how can I pass this dictionary to the behavior from XAML or its code behind
Solution
To take a Binding, a property needs to be a DependencyProperty
.
You need to define the property, in the Behaviour, like so:
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));
Use the Visual Studio "propdp" snippet.
Usage is as Adi said, like so:
<Interactivity:Interaction.Behaviors>
<Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" />
</Interactivity:Interaction.Behaviors>
OTHER TIPS
All you need to do is declare the dictionary as a property and then pass it a value via binding.
In the behavior:
public Dictionary<string, int> DataToCheckAgainst { get; set; }
In XAML:
<Interactivity:Interaction.Behaviors>
<Behaviors:KeyBoardChangeBehavior DataToCheckAgainst="{Binding MyDictionary}" />
</Interactivity:Interaction.Behaviors>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow