Skip to content

Instantly share code, notes, and snippets.

@usausa
Created February 16, 2018 07:35
Show Gist options
  • Save usausa/62c9f57674b041cfe74a51a67e6caec9 to your computer and use it in GitHub Desktop.
Save usausa/62c9f57674b041cfe74a51a67e6caec9 to your computer and use it in GitHub Desktop.
Attached property binding
<Window x:Class="WpfApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Label Content="{Binding Path=Content.(local:ViewProperty.Title), Mode=OneWay, Source={x:Reference Container}}"/>
<Button Content="Button1" Click="Button1_Click"/>
<Button Content="Button2" Click="Button2_Click"/>
<ContentControl x:Name="Container" Height="100"/>
</StackPanel>
</Window>
namespace WpfApp
{
using System.Windows;
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
Container.Content = new UserControl1();
}
private void Button2_Click(object sender, RoutedEventArgs e)
{
Container.Content = new UserControl2();
}
}
}
<UserControl x:Class="WpfApp.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="Blue"
local:ViewProperty.Title="Test1">
<Grid>
</Grid>
</UserControl>
<UserControl x:Class="WpfApp.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="Red"
local:ViewProperty.Title="Test2">
<Grid>
</Grid>
</UserControl>
namespace WpfApp
{
using System.Windows;
public static class ViewProperty
{
public static DependencyProperty TitleProperty = DependencyProperty.RegisterAttached(
"Title",
typeof(string),
typeof(ViewProperty),
new PropertyMetadata(string.Empty));
public static string GetTitle(DependencyObject obj)
{
return (string)obj.GetValue(TitleProperty);
}
public static void SetTitle(DependencyObject obj, string value)
{
obj.SetValue(TitleProperty, value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment