Attaching Behaviour to MetroWindow fails and results in wrong Style - c#

I have a simple test application that shows a simple Mahapps MetroWindow with an attached Behaviour. The problem is when attaching the Behaviour the outer border of the Mahapps MetroWindow is drawn.
<controls:MetroWindow x:Class="Desktop.Shell.Modern.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:cal="http://www.caliburnproject.org"
xmlns:modern="clr-namespace:Desktop.Shell.Modern"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Height="350"
Width="525"
ResizeMode="CanResizeWithGrip"
WindowTransitionsEnabled="True"
ShowIconOnTitleBar="False"
TitleCaps="False"
GlowBrush="{DynamicResource WindowTitleColorBrush}" >
<i:Interaction.Behaviors>
<modern:SomeBehavior SomeKey="{Binding Key}" />
</i:Interaction.Behaviors>
<ContentControl cal:View.Model="{Binding ActiveItem}" />
</controls:MetroWindow>
When removing the Behaviour everything looks as expected:
... but the Behaviour itself did nothing (yet). Here is the code of the SomeBehaviour class:
public sealed class SomeBehavior : Behavior<Window>
{
public static readonly DependencyProperty SomeKeyProperty =
DependencyProperty.Register(
"SomeKey",
typeof(Key),
typeof(SomeBehavior),
new PropertyMetadata(default(Key)));
public Key SomeKey
{
get
{
return (Key)this.GetValue(SomeKeyProperty);
}
set
{
this.SetValue(SomeKeyProperty, value);
}
}
protected override void OnAttached()
{
base.OnAttached();
}
protected override void OnDetaching()
{
base.OnDetaching();
}
}
Am I doing something wrong? Should I attach the Behaviour in a different way than attaching them to "normal" Windows?

That's because Mahapps.Metro sets its required behaviours in the window style, see MetroWindow.xaml.
If you want to attach additional behaviors, you have to copy these behaviours to your window, e.g.
<controls:MetroWindow x:Class="Desktop.Shell.Modern.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
xmlns:cal="http://www.caliburnproject.org"
xmlns:modern="clr-namespace:Desktop.Shell.Modern"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:Behaviours="http://metro.mahapps.com/winfx/xaml/shared"
Height="350"
Width="525"
ResizeMode="CanResizeWithGrip"
WindowTransitionsEnabled="True"
ShowIconOnTitleBar="False"
TitleCaps="False"
GlowBrush="{DynamicResource WindowTitleColorBrush}" >
<i:Interaction.Behaviors>
<modern:SomeBehavior SomeKey="{Binding Key}" />
<Behaviours:BorderlessWindowBehavior />
<Behaviours:WindowsSettingBehaviour />
<Behaviours:GlowWindowBehavior />
</i:Interaction.Behaviors>
<ContentControl cal:View.Model="{Binding ActiveItem}" />
</controls:MetroWindow>

Related

C# WPF use properties from different usercontrol as Command parameter

I have a problem with referencing properties or elements on different user controls in my MVVM WPF application.
Edit: Reduced code to a MCVE (hopefully). Also removed PropertyChanged Events to reduce code.
TLDR
I split up all my MainWindow.xaml elements to different user controls
In the menubar (one control) I want to fire a ICommand to save a Settings object (which is the datacontext of the MainWindow
For the method that is called in the Command I need a value from a completely different UserControl that is neither parent nor child of the menubar
How can I retrieve the value from the PasswordBox in a MVVM approach (most preferably as the CommandParameter on the MenuBar)?
View
MainWindow.xaml
<Window x:Class="WpfApp1.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:ViewModel="clr-namespace:WpfApp1.ViewModel"
xmlns:View="clr-namespace:WpfApp1.View"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<ViewModel:SettingsViewModel/>
</Window.DataContext>
<StackPanel>
<DockPanel>
<View:MenuBar DataContext="{Binding}"/>
</DockPanel>
<TabControl>
<TabItem Header="Tab1" DataContext="{Binding AppSettings}">
<View:TabItemContent/>
</TabItem>
</TabControl>
</StackPanel>
</Window>
The MenuBar which is supposed to bind on ICommand properties on the ViewModel (the DataContext of MainWindow).
MenuBar.xaml
<UserControl x:Class="WpfApp1.View.MenuBar"
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:WpfApp1.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" >
<Menu DockPanel.Dock="Top" Height="Auto" >
<!-- In the command I need a reference to the password on the tabItem -->
<MenuItem Name="SaveItem" Height="Auto" Header="Save"
Command="{Binding SaveCommand}"
CommandParameter="Binding RelativeSource=
{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Menu>
</UserControl>
TabItemContent.xaml
<UserControl x:Class="WpfApp1.View.TabItemContent"
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:WpfApp1.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
DataContext="{Binding PasswordSettings}">
<Grid>
<PasswordBox Height="25" Width="100" />
</Grid>
</UserControl>
In TabItemControl.xaml.cs I tried to introduce a Dependency Property and set the value to the datacontext of the control.
ViewModel
SettingViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using WpfApp1.Commands;
using WpfApp1.Model;
namespace WpfApp1.ViewModel
{
public class SettingsViewModel
{
public Settings AppSettings { get; private set; } = new Settings();
public ICommand SaveCommand { get; private set; }
public SettingsViewModel()
{
SaveCommand = new DelegateCommand( SaveSettings );
// load settings and call
// OnPropertyChanged( "AppSettings" );
}
public void SaveSettings( object o = null )
{
if( o is string encryptedPass )
{
// get the password and save it to AppSettings object
}
// call save method on settings
}
}
}
Model (Setting classes)
AppSetting.cs (encapsulating all the setting objects from the other tabs)
namespace WpfApp1.Model
{
public class Settings
{
public PasswordSettings PwSettings { get; set; } = new PasswordSettings();
}
}
PasswordSettings.cs
namespace WpfApp1.Model
{
public class PasswordSettings
{
public string EncryptedPass { get; set; }
}
}
and finally the DelegateCommand implementation in
DelegateCommand.cs see this gist

New UserControl not showing up

I have UserControl called "LinqView" where I have menu with buttons.
After user click button I want to display new UserControl using MVVM.
I have created new model class called "UsersModel" and new UserControl called "ViewUsersUserControl".
But I don't know why is not working.
Below is my xaml & cs code.
LinqView.xaml
<UserControl x:Class="LayoutMVVM.Views.LinqView"
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:LayoutMVVM.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:veiwmodels="clr-namespace:LayoutMVVM.ViewModels.MojeDBModel"
xmlns:views="clr-namespace:LayoutMVVM.Views.MojeDBViews" >
<UserControl.Resources>
<DataTemplate x:Name="UsersTemp" DataType="{x:Type veiwmodels:UsersModel}">
<views:ViewUsersUserControl DataContext="{Binding}" />
</DataTemplate>
</UserControl.Resources>
<Grid Background="LemonChiffon">
<Menu Height="32" Name="Menu" VerticalAlignment="Top">
<MenuItem Header="_Menu">
<MenuItem Header="Add User" Click="MenuItem_VU" />
</MenuItem>
</Menu>
</Grid>
</UserControl>
LinqView.cs
private void MenuItem_VU(object sender, RoutedEventArgs e)
{
DataContext = new UsersModel();
}
Tried like this?
<UserControl x:Class="LayoutMVVM.Views.LinqView"
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:LayoutMVVM.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:veiwmodels="clr-namespace:LayoutMVVM.ViewModels.MojeDBModel"
xmlns:views="clr-namespace:LayoutMVVM.Views.MojeDBViews" >
<UserControl.Resources>
<DataTemplate DataType="{x:Type veiwmodels:UsersModel}">
<views:ViewUsersUserControl DataContext="{Binding}" />
</DataTemplate>
</UserControl.Resources>
<Grid Background="LemonChiffon">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Menu " Height="32" Name="Menu" VerticalAlignment="Top">
<MenuItem Header="_Menu">
<MenuItem Header="Add User" Click="MenuItem_VU" />
</MenuItem>
</Menu>
<ContentControl Grid.Row="1" Content="{Binding UsersModel}"/>
</Grid>
</UserControl>
and your C# class should look like,
public class MainViewModel
{
public UsersModel UsersModel {get;set;}
// other properties
}
and in menu click,
private void MenuItem_VU(object sender, RoutedEventArgs e)
{
DataContext = new MainViewModel();
}
i have removed key on DataTemplate.
Update:
Simple working sample,
MainWindow.cs
namespace WpfApplication29
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
public class MainViewModel : INotifyPropertyChanged
{
public LinqViewModel LinqModel
{
get; set;
} = new LinqViewModel();
public MainViewModel()
{
SelectedMainModel = LinqModel;
}
private object selectedModel;
public object SelectedMainModel
{
get
{
return selectedModel;
}
set
{
selectedModel = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string name)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
public class LinqViewModel : INotifyPropertyChanged
{
public UserModel UserModel
{
get; set;
} = new UserModel();
private object selectedChildModel;
public object SelectedChildModel
{
get
{
return selectedChildModel;
}
set
{
selectedChildModel = value;
Notify("SelectedChildModel");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string name)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
public class UserModel
{
}
}
MainWindow.xaml
<Window
x:Class="WpfApplication29.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:local="clr-namespace:WpfApplication29"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Window.Resources>
<DataTemplate DataType="{x:Type local:LinqViewModel}">
<local:LinqView />
</DataTemplate>
<DataTemplate DataType="{x:Type local:UserModel}">
<local:UserView />
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding SelectedMainModel}" />
</Grid>
</Window>
User UserControl
<UserControl
x:Class="WpfApplication29.UserView"
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:local="clr-namespace:WpfApplication29"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid >
<TextBlock Text="From UserView"/>
</Grid>
</UserControl>
LinqView Usercontrol xaml
<UserControl
x:Class="WpfApplication29.LinqView"
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:local="clr-namespace:WpfApplication29"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
d:DesignHeight="300"
d:DesignWidth="300"
mc:Ignorable="d">
<Grid Background="LemonChiffon">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Menu Height="32" Name="Menu" VerticalAlignment="Top">
<MenuItem Header="_Menu">
<MenuItem Header="Add User" Click="MenuItem_VU" />
</MenuItem>
</Menu>
<ContentControl Grid.Row="1" Content="{Binding SelectedChildModel}"/>
</Grid>
</UserControl>
Linqview usercontrol cs
namespace WpfApplication29
{
/// <summary>
/// Interaction logic for LinqView.xaml
/// </summary>
public partial class LinqView : UserControl
{
public LinqView()
{
InitializeComponent();
}
private void MenuItem_VU(object sender, RoutedEventArgs e)
{
(this.DataContext as LinqViewModel).SelectedChildModel = (this.DataContext as LinqViewModel).UserModel;
}
}
}
this sample follows multilevel hierarchy. hope this helps.
If you have only one UsersModel you dont need to have it as resource template:
<UserControl x:Class="LayoutMVVM.Views.LinqView"
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:LayoutMVVM.Views"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
xmlns:veiwmodels="clr-namespace:LayoutMVVM.ViewModels.MojeDBModel"
xmlns:views="clr-namespace:LayoutMVVM.Views.MojeDBViews" >
<DockPanel Background="LemonChiffon">
<Menu Height="32" Name="Menu" DockPanel.Dock="Top">
<MenuItem Header="_Menu">
<MenuItem Header="Add User" />
</MenuItem>
</Menu>
<views:ViewUsersUserControl />
</DockPanel>
</UserControl>

CommandParameter is always NULL

I want to implement a simple Close Button in a WPF Window. The Window basically looks like this:
<Window x:Class="MyApplication.MainWindow"
xmlns=""....
...."
Title="MainWindow" WindowState="Maximized" WindowStartupLocation="CenterScreen" x:Name="mainWindow">
<DockPanel LastChildFill="True">
<Ribbon DockPanel.Dock="Top">
<Ribbon.ApplicationMenu>
<RibbonApplicationMenu SmallImageSource="Resources/menu_16x16.png">
<RibbonApplicationMenu.FooterPaneContent>
<RibbonButton Label="Beenden"
Command="{Binding CmdCloseApp}"
CommandParameter="{Binding ElementName=mainWindow}"
SmallImageSource="Resources/ende_16x16.png"
HorizontalAlignment="Right"/>
</RibbonApplicationMenu.FooterPaneContent>
</RibbonApplicationMenu>
</Ribbon.ApplicationMenu>
</Ribbon>
</DockPanel>
</Window>
DataContext of this Window ist set in it's Code-behindt to an instance of MainWindowViewModel
MainWindowViewModel:
public class MainWindowViewModel
{
public ICommand CmdCloseApp { get; set; }
public MainWindowViewModel()
{
CmdCloseApp = new RelayCommand<Window>(CloseApp);
}
public void CloseApp(Window w)
{
w.Close();
}
}
In CloseAppw is always null. Alle the other commands with string paramters, etc.. work perfectly - my only problem is that i don't get the window element does not find a way to my viewmodel.
thanks for your help!
EDIT
I am so sorry, i tried it with a simple button and it worked - The problem only occurs with RibbonButton
Edit: After your change to application menu RibbonButton your issue is that Microsoft RibbonControlLibrary uses a popup menu to hold the button, and the MainWindow is not part (parent of) of the popup menu's visual tree, so your ElementName binding can not find the "mainWindow" window, so it assigns null to CommandParameter
You could use static Application.Current to get MainWindow, then it will work.
NB! MainWindow is the Application property name, not the name of your window
<Window x:Class="WpfRelayCommandParameter.MainWindow"
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:wpfRelayCommandParameter="clr-namespace:WpfRelayCommandParameter"
xmlns:ribbon="http://schemas.microsoft.com/winfx/2006/xaml/presentation/ribbon"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance wpfRelayCommandParameter:MainWindowViewModel}"
Title="MainWindow" Height="350" Width="525"
x:Name="mainWindow">
<DockPanel LastChildFill="True">
<DockPanel LastChildFill="True">
<ribbon:Ribbon DockPanel.Dock="Top">
<ribbon:Ribbon.ApplicationMenu>
<ribbon:RibbonApplicationMenu SmallImageSource="Resources/AppMenu.png">
<ribbon:RibbonApplicationMenu.FooterPaneContent>
<ribbon:RibbonButton Label="Beenden"
Command="{Binding CmdCloseApp}"
CommandParameter="{Binding MainWindow, Source={x:Static Application.Current}}"
SmallImageSource="Resources/Exit.png"
HorizontalAlignment="Right" Click="ButtonBase_OnClick"/>
</ribbon:RibbonApplicationMenu.FooterPaneContent>
</ribbon:RibbonApplicationMenu>
</ribbon:Ribbon.ApplicationMenu>
</ribbon:Ribbon>
</DockPanel>
</DockPanel>
Personally I prefer callbacks to the window to go through an interface that can be custom to your view model needs, and can be mocked in unit tests:
<Window x:Class="WpfRelayCommandParameter.MainWindow"
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:wpfRelayCommandParameter="clr-namespace:WpfRelayCommandParameter"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance wpfRelayCommandParameter:MainWindowViewModel}"
Title="MainWindow" Height="350" Width="525"
x:Name="mainWindow">
<Grid>
<Button Content="Close Window"
Command="{Binding CmdCloseApp}"
VerticalAlignment="Top"
HorizontalAlignment="Left" />
</Grid>
Code
public partial class MainWindow : Window, IMainWindow
{
public MainWindow()
{
DataContext = new MainWindowViewModel(this);
InitializeComponent();
}
}
public interface IMainWindow
{
void Close();
}
public class MainWindowViewModel
{
private readonly IMainWindow _mainWindow;
public MainWindowViewModel() : this(null)
{
// Design time
}
public MainWindowViewModel(IMainWindow mainWindow)
{
_mainWindow = mainWindow;
CmdCloseApp = new RelayCommand(CloseApp);
}
public ICommand CmdCloseApp { get; set; }
public void CloseApp(object parameter)
{
_mainWindow.Close();
}
}
Note possible issues with type and null for CanExecute CanExecute on RelayCommand

How to instantiate UserControl and add Items to its Container in XAML

I have the following UserControl:
<UserControl x:Class="UserControlTest.UserControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel x:Name="MainPanel" Background="White">
<TextBlock Text="BasePanel"/>
</StackPanel>
And my MainWindwo.XAML:
<Window x:Class="UserControlTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UC="clr-namespace:UserControlTest"
Title="MainWindow" Height="350" Width="525">
<DockPanel Name="dpMain">
<UC:Control x:Name="ucBaseControl" />
</DockPanel>
In the code-behind MainWindow.xaml.cs:
namespace UserControlTest
{
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TextBox tbWorld = new TextBox();
tbWorld.Text = "Hello World";
ucBaseControl.MainPanel.Children.Add(tbWorld);
}
}
}
Is there a way to achieve this in XAML to avoid code-behind?
Thank you very much in advance!
You could try to do something like:
XAML:
<UserControl x:Class="WpfApplication1.BaseControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel x:Name="root">
<TextBlock>I'm from base</TextBlock>
<StackPanel x:Name="newPanel">
</StackPanel>
</StackPanel>
</UserControl>
Code behind:
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace WpfApplication1
{
[ContentProperty("NewControls")]
public partial class BaseControl : UserControl
{
public UIElementCollection NewControls
{
get { return (UIElementCollection)GetValue(NewControlsProperty); }
set { SetValue(NewControlsProperty, value); }
}
public static readonly DependencyProperty NewControlsProperty = DependencyProperty.Register("NewControls", typeof(UIElementCollection), typeof(BaseControl));
public BaseControl()
{
InitializeComponent();
this.NewControls = new UIElementCollection(this, this);
this.Loaded += BaseControl_Loaded;
}
void BaseControl_Loaded(object sender, RoutedEventArgs e)
{
foreach (UIElement element in NewControls.Cast<UIElement>().ToList())
{
NewControls.Remove(element);
this.newPanel.Children.Add(element);
}
}
}
}
And in the other control or window:
xmlns:local="clr-namespace:WpfApplication1"
...
<local:BaseControl>
<TextBlock>I'm from new</TextBlock>
</local:BaseControl>
Not sure it perfectly fits your needs but may serve as a good base.
Here my solution.
My UserControl:
<UserControl x:Class="ucFancyMenu" x:Name="MySelf"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Label Height="30" VerticalAlignment="Top" Background="#F0F">So Fancy</Label>
<ItemsControl Margin="0 30 0 0" ItemsSource="{Binding ElementName=MySelf, Path=Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</UserControl>
The UserControl Class:
<Markup.ContentProperty("Items")> _
Public Class ucFancyMenu
Public Property Items As New List(Of UIElement)
End Class
How to use it in other Xamls:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<local:ucFancyMenu>
<Button>FancyBtn 1</Button>
<Button>FancyBtn 2</Button>
<Button>FancyBtn 3</Button>
<Button>FancyBtn 4</Button>
<Button>FancyBtn 5</Button>
<Button>FancyBtn 6</Button>
<Button>FancyBtn 7</Button>
</local:ucFancyMenu>
</Grid>
</Window>

Custom Control Dependency Property Binding to Property

Just playing around with different types of bindings and having a property binding a Dependency Property of my custom control to another property.
XAML:
<UserControl x:Class="BrickBreaker.Brick"
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"
mc:Ignorable="d"
d:DesignHeight="20" d:DesignWidth="50" >
<Rectangle Width="50" Height="20" RadiusX="3" RadiusY="3" Stroke="Black" Fill="{Binding BrickFill, Mode=TwoWay}" />
Code Behind:
public partial class Brick : UserControl
{
public Brick()
{
InitializeComponent();
}
public Brush BrickFill
{
get { return (Brush)GetValue(BrickFillProperty); }
set { SetValue(BrickFillProperty, value); }
}
// Using a DependencyProperty as the backing store for BrickFill. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BrickFillProperty =
DependencyProperty.Register("BrickFill", typeof(Brush), typeof(Brick), null);
}
Implemenation In MainWindow.xaml
<UserControl x:Class="BrickBreaker.MainPage"
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:BrickBreaker="clr-namespace:BrickBreaker" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<BrickBreaker:Brick Margin="100,100,0,0" BrickFill="Azure"/>
</Grid>
Basically I want to bind the Rectangles Fill Property to the Dependency Property in the code behind.
Thanks.
Steve
What is the exact problem? Set DataContext of UserControl to code-behind, such as:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>
Missing this: DataContext="{Binding RelativeSource={RelativeSource Self}}"

Categories