为什么不';t在本地窗口资源中使用时绑定到属性有效
本文关键字:绑定 有效 属性 资源 窗口 为什么不 | 更新日期: 2023-09-27 17:59:15
我在MainWindow.xaml窗口中有一个带有动画的故事板。参考资料部分:
<Window.Resources>
<Storyboard x:Key="ShowSearchGrid">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Height)" Storyboard.TargetName="SearchGrid">
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="{Binding ExpandedGridHeight}"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
属性ExpandedGridHeight是在一个自定义类中定义的,如:
class ExpandedGridHeightClass : INotifyPropertyChanged
{
//The next bit handles the INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propertyName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public Double ExpandedGridHeight
{
get { return _expandedGridHeight; }
set
{
if (value != _expandedGridHeight)
{
_expandedGridHeight = value;
Notify("ExpandedGridHeight");
}
}
}
private Double _expandedGridHeight = 100;
}
窗口的数据上下文在MainWindow()中设置:
ExpandedGridHeightClass ExpandedHeight;
public MainWindow()
{
InitializeComponent();
ExpandedHeight = new ExpandedGridHeightClass();
this.DataContext = ExpandedHeight;
}
ExpandedHeight的ExpandedGridHeight属性的实际值在其他地方设置,并根据窗口的大小而更改。
故事板从以下功能启动:
void showSearchGrid()
{
Storyboard ShowSearchGrid = this.FindResource("ShowSearchGrid") as Storyboard;
ShowSearchGrid.Begin();
}
当我试图将该属性绑定到其他各种位置(如窗口的标题)时,它运行得很好,并完全按照预期进行了更新。然而,当它像代码示例中那样绑定到本地资源中的一个属性时,它就不起作用了:动画确实像往常一样开始,但SearchGrid的动画没有设置为ExpandedGridHeight,而是设置为高度值0。我怀疑这是因为动画是在资源中定义的,但不知道这个问题的解决方案。如有任何帮助,我们将不胜感激!:)
我只是想把它作为一个答案。这种方法肯定很"俗气",所以可能不符合你的喜好。
展开网格高度类:
class ExpandedGridHeightClass : INotifyPropertyChanged
{
private static ExpandedGridHeightClass _instance;
public static ExpandedGridHeightClass Instance
{
get
{
if (_instance == null)
_instance = new ExpandedGridHeightClass();
return _instance;
}
}
/**
* Whatever your class already has
*/
}
XAML:
<EasingDoubleKeyFrame KeyTime="0:0:0.5"
Value="{Binding ExpandedGridHeight, Source={x:Static MyNamespace:ExpandedGridHeightClass.Instance}}"/>