0

如果我在ViewModel类中有一个布尔变量,可以说

public bool test = true;(这是在 C# 中)

XAML/Expression Blend 中是否有任何方法来获取此变量并将其更改为 false USING PURELY XAML,没有后面的代码或任何东西?

我想为鼠标悬停事件执行此操作。如果鼠标悬停在某个对象上,则布尔变量应变为假,否则应保持真。

4

1 回答 1

0

答案1(最简单):

为什么不这样做?

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

我知道您想在所有 XAML 中执行此操作,但由于您已经声明了该属性,您不妨这样做而不是说。

public bool Test = false;

答案 2(更多代码,从长远来看更好的 MVVM 方法):

基本上,您在 Window1 上创建了一个依赖属性(称为 Test),在 XAML 端,您为 Window1 创建了一个样式,说明它的 Test 属性将与按钮 IsMouseOver 属性相同(我离开了 myButton_MouseEnter 事件,所以你可以在鼠标悬停在按钮上时检查变量的状态,我检查了自己,它确实更改为 true,您可以删除 MouseEnter 处理程序,它仍然可以工作)

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;
        }
    }
于 2009-09-16T20:23:51.870 回答