在代码中设置“依赖属性”

时间:2010-03-29 15:04:44

标签: wpf binding code-behind dependency-properties

我今天开始了......

我有以下代码在名为ActionScreen的类中声明依赖项属性:

#region Dependency Properties & Methods

public string DescriptionHeader
{
    get { return (string)GetValue(DescriptionHeaderProperty); }
    set { SetValue(DescriptionHeaderProperty, value); }
}

// Using a DependencyProperty as the backing store for DescriptionHeader.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty DescriptionHeaderProperty =
    DependencyProperty.Register("DescriptionHeader", typeof(string), typeof(ActionScreen), new UIPropertyMetadata("xxx"));

#endregion

我在我的Xaml中绑定到此属性,如下所示:

                    <GridViewColumn DisplayMemberBinding="{Binding Description}" Header="{Binding DescriptionHeader}" Width="350" />

现在我希望能够在接收事件时从我的代码中设置参数 - 但它不起作用:

public string DescColText { set { this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate() { DescriptionHeader = value; })); } }

2 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。似乎依赖属性更改不会触发该属性实际上已更改的通知。您必须手动执行此操作。在您的代码中,实现INotifyPropertyChanged接口,并在依赖项属性注册中添加PropertyChangedCallback委托。 (实施例)

public static readonly DependencyProperty DescriptionHeaderProperty = DependencyProperty.Register("DescriptionHeader", typeof(string), typeof(ActionScreen), new UIPropertyMetadata("xxx", new PropertyChangedCallback(DisplayTextChange)));

    private static void DisplayTextChange(DependencyObject dpo, DependencyPropertyChangedEventArgs args)
            {
                ((WhatEverYourClassNameIs)dpo).NotifyPropertyChanged("DescriptionHeader");

            }

以下是INotifyPropertyChanged实现的示例

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(info));
    }
}

这应该允许您的UI看到发生了更改。

答案 1 :(得分:0)

嗨解决了这个问题,我没有设置页面的datacontext。

显然我需要做

this.DataContext = this;