【问题标题】:WPF/XAML/C# Setting a Boolean variable on MouseOverWPF/XAML/C# 在 MouseOver 上设置布尔变量
【发布时间】:2010-11-28 22:16:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • 通常您在 ViewModel 中处理这个以使数据绑定更容易。如果您不想翻转 ViewModel 中的布尔值,您可以编写一个自定义控件,该控件具有按您喜欢的方式工作的 MouseOver 属性。使用此控件的客户端将不需要任何代码,因为在控件中处理。另一种选择是在绑定中使用 ValueConverter 来翻转 bool 值。
  • 为什么你的 ViewModel 想知道鼠标是否在一个用来显示它的一部分的控件上?

标签: wpf xaml mouseover


【解决方案1】:

答案 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;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多