WPF - Creating a custom control with dynamic subcontrols - wpf

I am attempting to create a menu/navigation control in WPF that will be used across several applications. The control is intended to reside in a custom window, and will provide the maximize, minimize, close, drag, etc functionality. In addition to the standard "window" functions, the control will should also contain the main "menu" of the application - essentially a collection of buttons that each associate with a command and/or viewmodel - these buttons are custom controls as well (derived from radio buttons).
Essentially, my goal is to be able to add this menu control and it's buttons via XAML in a manner like this (this is pseudocode, to be clear):
<MenuControl Title="ApplicationTitle>
<MenuControl.MenuButtons>
<MenuButton Content="Button1" Command="Command1"/>
<MenuButton Content="Button2" Command="Command2"/>
</MenuControl.MenuButtons>
</MenuControl>
I've gotten to the point where I can get this working correctly for only ONE button. Once I add a second button, I get a "Specified argument was out of the range of the valid values" from my XAML.
Here is the code-behind related to the menu on my custom control:
private static readonly DependencyProperty MenuProperty = DependencyProperty.Register("Menu", typeof(ObservableCollection<NavigationButton>), typeof(CCTNavigationHeader), new FrameworkPropertyMetadata(new ObservableCollection<NavigationButton>()));
public ObservableCollection<NavigationButton> Menu
{
get
{
return (ObservableCollection<NavigationButton>)GetValue(MenuProperty);
}
set
{
SetValue(MenuProperty, value);
}
}
And here is the XAML:
<ItemsControl ItemsSource="{Binding ElementName=ctlCCTNavigationHeader, Path=Menu}"/>
This is the code utilizing the control that works, with only one button:
<Controls:CCTNavigationHeader Title="Test">
<Controls:CCTNavigationHeader.Menu>
<Controls:NavigationButton Content="Test"/>
</Controls:CCTNavigationHeader.Menu>
</Controls:CCTNavigationHeader>
And this is the code using the control that chokes, once I add a second button:
<Controls:CCTNavigationHeader Title="Test">
<Controls:CCTNavigationHeader.Menu>
<Controls:NavigationButton Content="Test"/>
<Controls:NavigationButton Content="Test"/>
</Controls:CCTNavigationHeader.Menu>
</Controls:CCTNavigationHeader>
I know I must be doing something incorrectly here, but I haven't been able to find any examples of accomplishing this type of solution anywhere. Can anyone familiar with creating custom user controls in WPF point me in the right direction?

Figured this one out. I wasn't initializing the Menu collection when creating the control. The following code fixed it:
public CCTNavigationHeader()
{
InitializeComponent();
Menu = new ObservableCollection<NavigationButton>(); //this line
}

Related

Referencing MainWindow's content in MaterialDesign's DialogHost

I'm developing a WPF application using Material Design in XAML library. I'd like to use a dialog box to display error messages. In the documentation I've read that in order to dimm and disable content behind the dialog box I have to put it in the DialogHost tag, right after DialogHost.DialogContent
This is what I have right now:
<Window>
<md:DialogHost>
<md:DialogHost.DialogContent>
Content of my dialog box
</md:DialogHost.DialogContent>
My window's content wrapped in grid.
</md:DialogHost>
</Window>
The problem is: I'm planning to add few more dialog boxes for different purposes and I don't really know how to do that, since I have to put the rest of the code inside the DialogHost tag, which in my opinion would be a bit messy.
Instead I would like to achieve something like this:
<Window>
<Grid>
<md:DialogHost>
<md:DialogHost.DialogContent>
Content of my dialog box
</md:DialogHost.DialogContent>
Reference somehow the rest of the window's content
</md:DialogHost>
Window's content
</Grid>
</Window>
I tried using ContentPresenter but I'm getting error saying that the property Content cannot be bound to visual element.
If the idea described above is impossible to do, how can I use more than 1 dialog boxes? Because nesting one in another would result in a big messy code.
You should first remove the <md:DialogHost.DialogContent>from your main window and create an <UserControl>for each dialog box you need.
In the ViewModel class using such a dialog you must instantiate this <UserControl> and provide this instance as parameter for the DialogHost.Show method.
Dim view As New MyDialog1() With {.DataContext = Me}
Dim obj as Object = Await MaterialDesignThemes.Wpf.DialogHost.Show(view)
if obj IsNot Nothing Then
'do something
EndIf
I this (VB) example an MyDialog1 View class is instantiated using the DataContext of the VieModel class allowing the View class to access ViewModel class properties. Then the DialogHost.Show method is invoked. The View class can provide user response which is evaluated after closig of the View class.

WPF: binding elements in main window and user control

I am new to WPF and MVVM and not sure how to solve this (probbaly simple) problem. I have a MainWindow with two regions: RibbonView and below it a TabControl (Telerik). I have big buttons in the ribbon control which are always enabled. For example, I have a button "Tenants" and when I click on this button I create a new tab item and place my TenantControl containing a GridView control (also from Telerik). Its content is automatically loaded.
Now I want to get the following to work: additionally I have some small buttons (Add, Delete, Clone etc) (Ribbon control) that are disabled by default and I want to enable these buttons when I select an item in a grid. Is the using of routed commands the proper way to solve the problem? How to enable a button in a main window if I select an item in a grid in own user control? And yes in a main window I have a reference to the user control. No need for code just a concept is needed - as I said before I am completelly new to WPF/MVVM.
Thanks for any help and best regards,
Erno
In my WPF Applications, I often use RibbonBars as well, but instead of creating different TabItems for the different views, I display them all in one place by using a ContentControl and then just changing the Content value to different view models which are then rendered as the relevant views:
In Mainview:
<ContentControl Content="{Binding ViewModel}" />
...
In MainViewModel:
ViewModel = new SomethingViewModel();
...
In App.xaml:
<DataTemplate DataType="{x:Type ViewModels:SomethingViewModel}">
<Views:SomethingView />
</DataTemplate>
In my MainViewModel class, I have a helper method:
private bool IsViewModelOfType<T>()
{
return ViewModel != null && ViewModel.GetType() == typeof(T);
}
This method is used in the ICommand.CanExecute property to enable and disable Commands dependant on the loaded view model:
public ICommand CopyTrackList
{
get { return new ActionCommand(action => ClipboardManager.SetClipboardText(
((ReleaseLabelCopyViewModel)ViewModel).TrackList), canExecute =>
IsViewModelOfType<ReleaseLabelCopyViewModel>() &&
((ReleaseLabelCopyViewModel)ViewModel).SomePropertyInChildViewModel == true); }
}

WPF How to handle Cut, Copy, Paste toolbar buttons with UserControls and WindowsFormsHost

I'm hoping someone out there can help me. I'm trying to convert a legacy winforms app to WPF using MVVM. I've broken up the main window of the application into 4 main UserControls. The UserControls display different types of data objects and each UserControl has it's own ViewModel. Some of the data objects are inter-changeable between the different UserControls, for instance 'User Control 1' can contain strings objects and so can 'User Control 2 and 'User Control 3' (see diagram below).
My question is how can I handle the Cut, Copy, Paste commands in the toolbar? To possibly make things more complicated, each UserControl can contain a selected object at the same time as the other UserControls contain a selected object and User Control 2 is a WindowsFormsHost wrapper around a winforms control.
So far I've tried using ApplicationCommands but I can't even get them to fire. I've pasted a snippet of the code I thought would work using the ApplicationCommands below. Any help with this would be really appreciated.
<Button Command="ApplicationCommands.Cut" />
and on the UserControls
<UserControl.CommandBindings>
<CommandBinding Command="ApplicationCommands.Cut" Executed="executed_Cut" CanExecute="canExecute_Cut" />
</UserControl.CommandBindings>
and finally in the UserControl's code behind (I know this isn't great)
public void executed_Cut(Object sender, ExecutedRoutedEventArgs e)
{
//execute code here
}
public void canExecute_Cut(Object sender, CanExecuteRoutedEventArgs e)
{
//can execute code here
}
I successfully use the behavior approach described in this question to avoid putting any code in my view model. Then whenever focus goes to a control which has a copy/paste behavior defined the toolbar cut/copy/paste buttons "light up" accordingly.

Silverlight call command from button within listbox item template

I have seen this question asked a few times but I have not seen been able to find a complete answer to my scenario.
Within my project I have a user control that I have created as a listbox item. Within this user control I have a button
<Button x:Name="DetailButton"
Grid.Column="1"
Width="107"
Height="23"
Margin="196,94,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="MoreDetail_Click"
Command="{Binding GetCFSDetailCommand}"
Content="View Details [+]" />
the button has a click event specific to the view this basically expands or collapses a grid row based upon the state of visibility. I used an event here since it was specific to the ui. This button also has a command which is called in the VM.
VM code
public class SearchViewModel : INotifyPropertyChanged
{
private DelegateCommand _getCFSDetailCommand;
public DelegateCommand GetCFSDetailCommand
{
get
{
if (this._getCFSDetailCommand == null)
this._getCFSDetailCommand = new DelegateCommand(GetCFSDetailCommandExecute, CanGetCFSDetailCommandExecute);
return this._getCFSDetailCommand;
}
}
private void GetCFSDetailCommandExecute(object parameter)
{
//bind collection to model call here
}
The issue I am having is the command on the button is "lost" or never called when inside the listbox item I have the view bound to the vm and if I place this command on any other button within the view the command is called. Can anyone help me understand how to call a Command bound to button within a listbox item?
Thank you in advance
randyc,
In your original (first) post you was binding the CommandParameter to a local data context of list item. In the second post you miss that binding, and I think it is impossible in the context of second port.
In your case I propose to use the Element to Element binding to bind to the GetCFSDetailCommand command from the parent data context.
The issue in calling a command within the usercontrol as a listbox item is that the pattern is looking for the command within the context of the control. Apparently the listbox item jumps outside of the visual tree and so binding is not inherited.
To correct this I needed to explicitly set the data context of the button to the ViewModel. This was ultimately solved using the Element to Element binding which allowed me to point the datacontext of the user control to the main view that contained it.
Hope this helps

Designing WPF UserControl that gets its DataContext from outer controls: How to have some sample data in designer but use inherited DC at runtime?

I am designing a WPF user control which contains other user controls (imagine a WidgetContainer, containing different Widgets) - using M-V-VM architecture.
During development, I have WidgetContainerView in a window, window (View) spawns a WidgetContainerViewModel as its resource, and in a parameterless constructor of WidgetContainerViewModel, I fill its exposed collection with some sample widgets (WidgetViewModels).
WidgetContainer control inherits the DataContext from window, and inside, there is a ListView, that binds Widgets to WidgetView control (which is inside ListView.ItemTemplate).
Now this works OK in my WindowView, as I see my sample widgets, but once I edit the WidgetContainerView or WidgetView, there is no content - at design time, controls are standalone, and they don't inherit any DataContext, so I don't see a content, and have troubles designing them (a ListView is empty, Widget's fields as well...).
I tried adding a sample widget to the WidgetView:
public partial class WidgetView : UserControl
{
public WidgetView()
{
InitializeComponent();
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
//btw, MessageBox.Show(...) here sometimes crashes my Visual Studio (2008), but I have seen the message - this code gets executed at design time, but with some lag - I saw the message on reload of designer, but at that time, I have already commented it - wtf?
this.DataContext = new WidgetViewModel(); //creates sample widget
}
}
}
but that didn't work - I still don't see anything in designer.
I also wanted to create a WidgetViewModel as a resource in WidgetView, like this:
<UserControl x:Class="MVVMTestWidgetsControl.View.WidgetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="WidgetViewModel" //this doesn't work!
Height="Auto" Width="Auto">
<UserControl.Resources>
<ResourceDictionary>
<ViewModel:WidgetViewModel x:Key="WidgetViewModel" />
</ResourceDictionary>
</UserControl.Resources>
<TextBlock Text="{Binding Path=Title}"></TextBlock>
</UserControl>
but I don't know how to assign a WidgetViewModel as a DataContext of a whole widget - I can't add DataContext attribute to UserControl, because WidgetViewModel is defined later in the code. Any ideas how to do this? I could use a sample data this way, and just override it in code so that it has the right content at runtime...
What are your best practices when developing user controls? Thank you, designing empty control is no fun :)).
In your second snippet, you should be able to refer to your DataContext as a DynamicResource:
DataContext="{DynamicResource WidgetViewModel}"
But most custom user controls have some sort of top level layout container, and you can set the DataContext on that container as a StaticResource.
In your case, however, you may want to consider dropping the VM portion of your code altogether since you're writing a custom UserControl. You should ask yourself what benefits are you gaining from a completely self-contained ViewModel with no real backing Model designed for just one View (i.e. the custom UserControl). Perhaps you could just define some DependencyProperties and use those?
I came up with several solutions: Add DC as resource (it will get automatically instantiated with parameterless constructor), and do the following in View's codebehind:
public PanelView()
{
InitializeComponent();
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) //DeleteAtRelease:
{
//we are in runtime, reset DC to have it inherited
this.DataContextHolder.DataContext = DependencyProperty.UnsetValue;
}
}
Better way would be to only assign DC if we are at designtime, but VS didn't like it - it worked only sometimes, and quite nondeterministically, and once it even crashed.
Other check for design time is:
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
this.DataContext = new WidgetViewModel();
}

Resources