tags:

views:

411

answers:

2

If i have a boolean in one of my ViewModel Class lets say

public bool test = true; (This is in C#)

Is there ANYWAY possible in XAML/Expression Blend that i can take this value and change it to

false BUT USING PURELY XAML, no code behind or anything.

I'm trying to do this for a mouse over event, but can't seem to be working. If a mouse is over a certain object, my boolean will turn false, otherwise it will remain true.

Thanks!

A: 

You may get few hints from this post on stackoverflow

Accessing code behind variables in XAML

rajesh pillai
+1  A: 

Answer 1 (easiest):

Why not do this?

public bool Test
{
    get { return myControl.IsMouseOver; }
}

I know you want to do it in all XAML, but since you're already declaring the property, you might as well do this instead of saying.

public bool Test = false;

Answer 2 (more code, MVVM approach which is better in the long run):

Here basically, you create a Dependency Property (called Test) on Window1, and on the XAML side, you create a style for Window1 that says that its Test property will be the same as the button IsMouseOver property (I left the myButton_MouseEnter event so you can check the state of the variable when the mouse is over the button, I checked myself and it does change to true, you can remove the MouseEnter handler, and it'll still work)

XAML:

<Window x:Class="StackOverflowTests.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" x:Name="window1" Height="300" Width="300"
    xmlns:local="clr-namespace:StackOverflowTests">
    <Window.Resources>
     <Style TargetType="{x:Type local:Window1}">
      <Setter Property="Test" Value="{Binding ElementName=myButton, Path=IsMouseOver}">
      </Setter>
     </Style>
    </Window.Resources>
    <Grid>
     <Button x:Name="myButton" Height="100" Width="100" MouseEnter="myButton_MouseEnter">
      Hover over me
     </Button>
    </Grid>
</Window>

C#:

public partial class Window1 : Window
    {
     public Window1()
     {
      InitializeComponent();
     }

     public bool Test
     {
      get { return (bool)GetValue(TestProperty); }
      set { SetValue(TestProperty, value); }
     }

     // Using a DependencyProperty as the backing store for Test.  This enables animation, styling, binding, etc...
     public static readonly DependencyProperty TestProperty =
      DependencyProperty.Register("Test", typeof(bool), typeof(Window1), new UIPropertyMetadata(false));

     private void myButton_MouseEnter(object sender, MouseEventArgs e)
     {
      bool check = this.Test;
     }
    }
Carlo