1

我有一个 Window shell,它基本上是:

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

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

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

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

我觉得这可以使用附加属性来实现。任何人都可以让我朝着正确的方向开始吗?

丹尼尔

4

2 回答 2

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

它设置包含窗口的标题。

于 2010-02-01T15:31:52.503 回答
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>
于 2010-02-01T12:50:56.113 回答