问题
I have a Window shell that is basically:
<Window>
<ContentPresenter Content="{Binding}" />
</Window>
Injected into the ContentPresenter at run-time are UserControls. What I want to be able to do is write:
<UserControl Window.Title="The title for my window">
[...]
</UserControl>
So that the Window title is updated using the UserControl
Window.Title
property.
I have a feeling this can be achieved using attached properties. Can anyone start me off in the right direction?
Daniel
回答1:
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>
回答2:
I ended up using the following:
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);
}
}
}
Which makes use of Philipp Sumi's code snippet to find the first ancestor Window: http://www.hardcodet.net/2008/02/find-wpf-parent
In my views I can now do:
<UserControl Behaviors:WindowTitleBehavior.WindowTitle="My Window Title">
And it sets the title of the containing Window.
来源:https://stackoverflow.com/questions/2176655/creating-a-window-title-attached-property