Reputation: 3000
What I am trying to do is to create a variable in my (xaml) control resources and bind it to a property on my DataContext (e.g. ViewModel).
I am willing to have in my xaml
, something like this
<system:Boolean x:Key="MyVariable" Value={Binding MyDataContextProperty}/>
I know that are more elegant ways to do it, e.g declare MyVariable
to DataContext (e.g. ViewModel) and use it from there. However for testing reasons I want to explore the aforementioned aspect.
Is that even possible?
Upvotes: 0
Views: 266
Reputation: 35646
A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
so no, <system:Boolean x:Key="MyVariable" Value={Binding MyDataContextProperty}/>
will not work
it is possible to declare a constant bool value in Resources
<StackPanel>
<StackPanel.Resources>
<system:Boolean x:Key="varBool">
True
</system:Boolean>
</StackPanel.Resources>
<CheckBox IsChecked="{StaticResource varBool}"/>
</StackPanel>
also possible to make a special DependencyObject
public class SomeObj: DependencyObject
{
public static DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof (bool), typeof (SomeObj),
new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public bool Value
{
get { return (bool)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
}
bindings will work
<StackPanel>
<StackPanel.Resources>
<local:SomeObj x:Key="varBool1" Value="True"/>
<local:SomeObj x:Key="varBool2" Value="{Binding Value, Source={StaticResource varBool1} }"/>
</StackPanel.Resources>
<CheckBox IsChecked="{Binding Value, Source={StaticResource varBool1}}"/>
<CheckBox IsChecked="{Binding Value, Source={StaticResource varBool2}}"/>
</StackPanel>
the main question is why do all this if there is already MyDataContextProperty
?
Upvotes: 1