创建Window.Title附加属性

时间:2010-02-01 12:44:01

标签: wpf wpf-controls binding attached-properties

我的Window shell基本上是:

<Window>
    <ContentPresenter Content="{Binding}" />
</Window>

在运行时注入ContentPresenter的是UserControls。我想要做的是写:

<UserControl Window.Title="The title for my window">
[...]
</UserControl>

使用UserControl Window.Title属性更新Window标题。

我觉得这可以使用附加属性来实现。谁能让我朝着正确的方向开始?

丹尼尔

2 个答案:

答案 0 :(得分:3)

C#:

public class MyUserControl : UserControl
{
   public static readonly DependencyProperty WindowTitleProperty = DependencyProperty.RegisterAttached("WindowTitleProperty",
                typeof(string), typeof(UserControl),
                new FrameworkPropertyMetadata(null, WindowTitlePropertyChanged));

        public static string GetWindowTitle(DependencyObject element)
        {
            return (string) element.GetValue(WindowTitleProperty);
        }

        public static void SetWindowTitle(DependencyObject element, string value)
        {
            element.SetValue(WindowTitleProperty, value);
        }

        private static void WindowTitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
                    Application.Current.MainWindow.Title = e.NewValue;
        }
}

XAML:

<UserControl namespace:MyUserControl.WindowTitle="The title for my window">
[...]
</UserControl>

答案 1 :(得分:3)

我最终使用了以下内容:

public static class WindowTitleBehavior
{
    public static readonly DependencyProperty WindowTitleProperty = DependencyProperty.RegisterAttached(
        "WindowTitleProperty", typeof(string), typeof(UserControl),
                 new FrameworkPropertyMetadata(null, WindowTitlePropertyChanged));

    public static string GetWindowTitle(DependencyObject element)
    {
        return (string)element.GetValue(WindowTitleProperty);
    }

    public static void SetWindowTitle(DependencyObject element, string value)
    {
        element.SetValue(WindowTitleProperty, value);
    }

    private static void WindowTitlePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UserControl control = d as UserControl;
        if (!control.IsLoaded)
        {
            control.Loaded += new RoutedEventHandler(setTitle);
        }
        setTitle(control);
    }

    private static void setTitle(object sender, RoutedEventArgs e)
    {
        UserControl control = sender as UserControl;
        setTitle(control);
        control.Loaded -= new RoutedEventHandler(setTitle);
    }

    private static void setTitle(UserControl c)
    {
        Window parent = UIHelper.FindAncestor<Window>(c);
        if (parent != null)
        {
            parent.Title = (string)WindowTitleBehavior.GetWindowTitle(c);
        }
    }
}

利用Philipp Sumi的代码片段找到第一个祖先窗口:http://www.hardcodet.net/2008/02/find-wpf-parent

在我的观点中,我现在可以这样做:

<UserControl Behaviors:WindowTitleBehavior.WindowTitle="My Window Title">

它设置了包含Window的标题。