我的应用程序(MVVM Light)调整了它的主窗口大小(隐藏并用动画显示它)。对于动画,我使用带有StaticResources参数的DataTrigger:
<Window.Resources>
<system:Double x:Key="WindowMaxWidth">400</system:Double>
<system:Double x:Key="WindowMinWidth">25</system:Double>
</Window.Resources>
<Window.Style>
<Style TargetType="Window">
<Style.Triggers>
<DataTrigger Binding="{Binding DropBox.IsShown}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Width"
To="{StaticResource WindowMaxWidth}"
Duration="0:0:0:0.2"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Width"
To="{StaticResource WindowMinWidth}"
Duration="0:0:0:0.2"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Style>
在我的ViewModel中,我需要窗口的宽度值,所以我绑定了它。问题是它默认为0,所以我必须用值初始化它。实际上我需要的是静态资源的值: WindowMaxWidth 。
我该怎么办?
答案 0 :(得分:2)
将WindowMaxWidth
和WindowMinWidth
放入您的视图模型中,并使用x:Static
引用它们:
namespace MyNamespace
{
class ViewModel
{
public static double WindowMaxWidth = 400;
public static double WindowMinWidth = 25;
}
}
导入正确的命名空间xmlns:myns="clr-namespace:MyNamespace"
<DoubleAnimation Storyboard.TargetProperty="Width"
To="{x:Static myns:ViewModel.WindowMaxWidth}"
Duration="0:0:0:0.2"/>
答案 1 :(得分:0)
您可以以这种方式使用代码(例如在构造函数中,在将DataContext设置为ViewModel之后):
(this.DataContext as MyViewModel).MyWindowWidth = (double)this.FindResource("WindowMaxWidth");