在本地窗口资源中使用时,为什么不绑定到属性?

时间:2016-07-28 17:39:54

标签: c# wpf xaml

我在MainWindow.xaml Window.Resources部分有一个带动画的故事板:

<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();
}

当我尝试将属性绑定到窗口标题等各种其他位置时,它完美地工作,并且完全按预期更新。但是,当它像代码示例中绑定到本地资源中的属性时,它不起作用:动画确实像往常一样启动,但不是动画到ExpandedGridHeight,而是将SearchGrid设置为高度值0。我怀疑这是因为动画是在资源中定义的,但不知道修复此问题。任何帮助,将不胜感激! :)

1 个答案:

答案 0 :(得分:0)

想到我不妨把它作为答案。这种方法绝对是&#34; hackish&#34;,所以它可能不符合你的喜好。

ExpandedGridHeightClass:

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}}"/>