【问题标题】:Animate Grid Margin on MainForm from Usercontrol来自用户控件的 MainForm 上的动画网格边距
【发布时间】:2018-09-08 20:55:25
【问题描述】:

我在父窗口(仪表板)上有一个用户控件(Menu.xaml),网格名称为“page”。 我在用户控件上还有一个按钮(ButtonOpenMenu),我想更改主窗体上网格(页面)的 Margin 属性。

基本上是这样

关于后面的 UserControl 代码

   public void ButtonOpenMenu_Click(object sender, RoutedEventArgs e)
        {
         //  change margin of grid on Parent Wndow(Dashboard)

ThicknessAnimation grdanimation =  new ThicknessAnimation(new thickness(0), new Thickness(200, 0, 0, 0),
       new Duration(new TimeSpan(0, 0, 1)), FillBehavior.HoldEnd);
Dashboard db = new Dashbaord();

        db.page.BeginAnimation(Border.MarginProperty, anima);


        } 

有什么帮助吗?

【问题讨论】:

  • 当您调用Dashboard db = new Dashbaord(); 时,您正在创建一个新的仪表板,这显然不是已经存在的仪表板。试试db = (Dashboard)Application.Current.MainWindow;
  • 如果Dashboard中的Grid是UserControl的直接父元素,也可以试试Parent.BeginAnimation(...)

标签: c# wpf data-binding


【解决方案1】:

找到了我的问题的解决方案。

所以在我的 Menu.xaml(用户控件)中,我创建了一个静态事件

// static
public static event EventHandler AnimateButtonClicked;

  // button click event
public void Animatebutton_Click(object sender, RoutedEventArgs e)
    {
        AnimateButtonClicked(this, e);
    }

然后在 MainWindow (Dashboard) 中。我创建了一个方法 (DoAnimate),当我的用户控件上的按钮 (Animatebutton) 被单击时会触发该方法。

    Dashboard.xaml

    private void DoAnimate(Object sender, EventArgs e)
    { 
        ThicknessAnimation anima =
        new ThicknessAnimation(new Thickness(0), new Thickness(150, 0, 0, 0),
        new Duration(new TimeSpan(0, 0, 1)), FillBehavior.HoldEnd);
        anima.From = new Thickness(150, 0, 0, 0);
        anima.To = new Thickness(100, 0, 0, 0);
        anima.AutoReverse = false;

        // page is the name of the grid that gets animated.
        page.BeginAnimation(Border.MarginProperty, anima);
    }

 private void Window_Loaded(object sender, RoutedEventArgs e)
    {
       Menu.AnimateButtonClicked += new EventHandler(DoAnimate);

    }

【讨论】:

  • AnimateButtonClicked 事件不能是静态的。您应该改为分配菜单的x:Name,如x:Name="menu",然后附加处理程序,如menu.AnimateButtonClicked += DoAnimate;
  • 我厌倦了使用 x 名称,但它一直给我错误:非静态字段、方法或属性“menu.AnimateButtonClicked”需要对象引用
猜你喜欢
  • 2012-01-09
  • 2014-11-18
  • 2011-05-29
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 2015-06-21
  • 1970-01-01
相关资源
最近更新 更多