Use databinding with the ToolBarTray control in WPF - c#

I’m working on a WPF/PRISM app. I started by creating a dynamic menu using databinding following that example: http://www.koaxkoaxkoax.com/ribbit/2010/09/creating-dynamic-menus-in-wpf.html
It uses a HierarchicalDataTemplate which seems like a nice solution.
I had the goal to use the same concept for toolbars but sadly the ToolBarTray control doesn’t have a ItemsSource to dynamically generate Toolbar controls in it.
I’m pretty new to WPF and I can’t seem to find a good solution to create toolbars inside a ToolBarTray using databinding. Does somebody have a solution?
Is it possible with HierarchicalDataTemplate?
Thank you

While the ToolBarTray does not contain an ItemsSource property, it does contain a ToolBars property that you'd be able to bind to. And then, each ToolBar has an ItemsSource property that you could bind to as well.
So your binding would look something like this:
<ToolBarTray ToolBars="{Binding MyToolBarsProperty}" />
Then you could start using HierarchicalDataTemplates on the Toolbars:
<HierarchicalDataTemplate.ItemContainerStyle>
<Style TargetType="Button">
<Setter Property="Command" Value="{Binding Command}"/>
</Style>
</HierarchicalDataTemplate.ItemContainerStyle>

Related

Apply Style to every element of type X in UWP

I'm currently trying to find a way to style all controls in a UWP app with the same Style/type. To be specific I want to set OpticalMarginAlignment to TrimSideBearings for every - I mean every TextBlock.
I know I can create a Style in App.xaml without x:Key property like this:
<Style TargetType="TextBlock">
<Setter Property="OpticalMarginAlignment" Value="TrimSideBearings" />
</Style>
But this does not change the style of TextBlocks which are in a DataTemplate (which according to similar questions is by design). However I don't want to have to set a Style for each TextBlock used in a DataTemplate, so I thought about other solutions:
Create a StyledTextBlock element derived from TextBlock (not working cause TextBlock is sealed)
Create a StyledDataTemplate element derived from DataTemplate (not working cause I haven't found anything in DataTemplate I could hook into to load the Style and because there is no DataTemplate.Resources)
Create a StyledTextBlock element derived from UserControl with a TextBlock element inside
Number 3 is even working, though it would require me to create a DependencyProperty for every TextBlock.DependencyProperty I want to use to style the StyledTextBlock like this:
<StyledTextBlock Text="Example" FontSize="10" />
To keep code amount low I could create a TextStyle DependencyProperty in StyledTextBlock and set it like this, but I don't like this solution as well:
<StyledTextBlock Text="Example">
<StyledTextBlock.TextStyle>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="10" />
</Style>
</StyledTextBlock.Style>
</StyledTextBlock>
Does anyone have another idea how to achieve this?

usercontrol (?) for WPF reusable menu

I am a beginner at WPF so please excuse me if this question is too simple :)
I have a listbox which I would like to filter by various filter conditions. This listbox I fill with instances of a particular type. Each filter condition is associated with one of the listbox items' properties. (They are like: this or that string property starts with string XXX.)
For this I would need a menu for each property from which users can select the filter conditions they want to filter the items with. Each property of the same type will have the very same set of menu items with the various filter conditions. (For strings: starts with, ends with... for ints: lower than, higher than, etc.)
The menus require some code behind too so I don't want to program these for each property separately.
My problem is that I don't know in what way could I program these. I cannot program them as UserControls because all what I need is MenuItems in a Menu. But I cannot program them as MenuItem derived classes because I would need the XAML for designing them for each type. Could I create a MenuItem derived class with a XAML somehow? Or do you have any other suggestions?
In WPF, we work with data elements whose public properties are data bound to the properties of various UI controls via DataTemplates. Please see the Data Templating Overview page on MSDN for the full story.
In order to do this, we develop custom classes that contain all of the necessary properties that we need to display and then we declare one or more DataTemplates that define the binding connections between the classes and the UI controls, or MenuItems in your case.
The benefit of this is that in order to display a Menu in the UI, you just need to data bind one of your custom menu class objects to a control in the UI and let the DataTemplate do the rest. So if you want to change the menu contents, you just need to change the data item that is data bound to the Menu.
So to answer your question directly, a Menu control would be most suitable for you to use, but you don't store the Menu properties in your code behind... you store the property values in your custom classes that will be data bound to the Menu control properties:
<Menu ItemsSource="{Binding CollectionOfYourCustomClassItems}" ... />
It is worth pointing out that you may need to set the child MenuItem properties in a Style and not a DataTemplate as usual (taken from the accepted answer to the WPF MenuItem : Mix databound items and static content question (which I recommend that you read) here on Stack Overflow):
<MenuItem Header="_Recent Files" ItemsSource="{Binding Commands,Mode=OneWay}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=ShortName}" />
<Setter Property="ToolTip" Value="{Binding Path=FileName}" />
<Setter Property="Command" Value="{Binding Path=OpenCommand}" />
<Setter Property="CommandParameter" Value="{Binding Path=OpenParameter}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSeparator}" Value="true">
<Setter Property="MenuItem.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
You will find many more tutorials and related questions regarding data binding to MenuItems online, so I won't go over everything again here. Please see the following article to start with:
Binding menus using HeirarchicalDataTemplates

How to get or set custom object as datacontext instance to custom control in wpf

I've created a custom control that is styled and configures in its own XAML sheet. Databindings in this control uses a specific object (CProject class).
Just to clarify, the control is a project frame, that has controls for settings and a canvas that will be the workspace for each/any project.
The project control (IPProjectPanel) inherits "Frame", and also adds a "settings" stack panel to its children list which in turn contains controls for - well, settings.
The CProject class however, is the pure functional part, with no UI interaction or handling whatsoever. So, I need to "plug" an instance of CProject into every unique project that can be active. So, I want to set a specific instance of CProject as datacontext to every IPProjectPanel instance in a tabpanel. Either I want to set the datacontext by code, or have it created by settings datacontext in XAML, and retrieving it after it has been initialized.
The problem though, is that I cant quite figure out either.
Here is a snippet of the style of the IPProjectPanel in XAML, that uses the approach to set datacontext in XAML:
<Style TargetType="{x:Type ip:IPProjectGrid}">
<Setter Property="OverridesDefaultStyle"
Value="True" />
<Setter Property="SnapsToDevicePixels"
Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ip:IPProjectGrid}">
<Grid Background="White"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Margin="0">
<!---->
<Grid.DataContext>
<ipp:CProject></ipp:CProject>
</Grid.DataContext>
<StackPanel x:Name="PART_settingsPanel"
HorizontalAlignment="Right"
VerticalAlignment="Stretch"
MinWidth="300" Background="Gray">
<GroupBox Header="Project settings">
<StackPanel>
....
</style>
Here it is set as a context to Grid, but I'd like to have it as a context of the actual class (IPProjectPanel).
So, the IPProjectPanel instance is created by code (for now..), and I need to retrieve the CProject instance (or set one) so that I can work with it.
I'd like to keep to C#/WPF ways to do stuff, as this app is also training for WPF and C# concepts and such. So the "best C#-WPF" way to do it, is very welcome, but a solution either way!
Thank you for your time.
So in general, the datacontext is primary inteded to be for your ViewModel, and in fact WPF is really set up for doing MVVM (Model View ViewModel) style applications. It's actually fairly simple to learn, but if you're looking for the "Best C#-WPF" way of doing things, take the time to learn MVVM. It's really fairly straightforward.
Simple Example from CodeProject:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
From Microsoft (somewhat heavy reading):
http://msdn.microsoft.com/en-us/library/gg405484(v=pandp.40).aspx
The way you have this set up currently has the potential to create some nasty bugs. You should never declare a DataContext object instance inside a template unless you never plan on accessing it outside of that template's scope. By doing so you will be creating a new instance of the CProject class any time the control needs to be visually re-loaded (like changing tabs) and you may end up referencing an old CProject instance in code while displaying a completely separate one on the screen. Declaring a DataContext object not in a template (i.e. Window.DataContext) is fine.
If you want each control instance to create its own CProject instance you would be better off doing that in code in the constructor and exposing that as a property on the control which you can then bind your Grid.DataContext to inside the template. Avoid setting it to the DataContext property of the control itself as this will cause any implicit source Bindings that are set on the control where it is declared in XAML to break by overriding the inherited DataContext:
Grid.DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=PropertyWithCProject}"
It's probably more likely that you will want to control the CProject instances externally and hand them to the control instances. To do this you can create them in a container ViewModel class (MVVM pattern) and set this as a DataContext higher up on something that will contain all of your custom controls. You can then expose individual CProjects or a collection of them and bind your controls' DataContexts to those.

WPF ContextMenu bind some property to another property of the same control

I have a ContextMenu and a ColumnHeaderStyle defined in Window.Resource section which I use-it to a DataGrid ColumnHeader. My code is something like this:
<ContextMenu x:Key="cm_columnHeaderMenu"/>
<Style x:Key="DefaultColumnHeaderStyle" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource cm_columnHeaderMenu}" />
</Style>
<DataGrid Grid.Column="2" Grid.Row="1" x:Name="dgridFiles" IsReadOnly="True"
ColumnHeaderStyle="{StaticResource DefaultColumnHeaderStyle}">
I want to know if I can (and if the answer it true, then HOW I can I do it) bind the ContextMenu Visibility property to same control ContextMenu Items.Count > 0 property.
Initially based on some other treeView control selections made there shoud be no items in the context menu, but i wish to add dinamically items in ContextMenu based on selection in treeView. This part is done, the context has those items. On some selections there are no-items, but still on the grid it appears an empty ContextMenu. So I believe the easiest part it would be to bind the Visibility to Items.Count property of the same control.
Sorry if my english is not good enough, I'll try to explain better if i didnt make clear 1st time.
you want to bind via RelativeSource, especially the Self mode.
I think by reading this or this you will be able to achieve your goal.
Then you'll need a binding converter to convert the integer values to the matching type and values of the Visibility property. You'll find a short tutorial here.
Regards
Using this you can bind to the property in the same control
Visibility="{Binding Path=Items.Count, RelativeSource={RelativeSource Self}}"
You also have to use a converter to achieve what you want.
Just in case you need this
Try a converter to convert the value of the item count to a boolean. So you'll end up with something like
<ContextMenu Visibility={Binding RelativeSource={RelativeSource Self},
Converter={StaticResource ItemsToVisibilityConverter}, Path=Items.Count}} />
If that doesn't work, try this with data triggers (you still need a converter anyway, and this shows a converter at work):
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a8ad8c14-95aa-4ed4-b806-d0ae874a8d26/

Issue with binding Collection type of dependency property in style

I have a customcontrol exposing a Dependency property of type ObservableCollection. When i bind this properrty directly as part ofthe control's mark up in hte containing control everythihng works fine
<temp:EnhancedTextBox
CollectionProperty="{Binding Path=MyCollection, Mode=TwoWay}"/>
But when i try to do the binding in the style created for the control it fails,
<Style x:Key="abc2"
TargetType="{x:Type temp:EnhancedTextBox}" >
<Setter Property="CollectionProperty"
Value="{Binding Path=MyCollection, Mode=TwoWay}"/>
</Style>
Please help !!!!!
Thanks
It has to do with your data context for the style. There is no way for the style to know where MyCollection is coming from because although you may have it defined in the same file, the style does not share the data context.
I would also ask the question as to why you are setting the property in the style? The style is not meant for this sort of operation. The style is supposed to control the look of the UI element not provide the functionality.

Categories