How can I bind to a parent UIElement within an ItemTemplate? - wpf

I'm trying to bind to a property of MainWindow, but from a ContextMenu within a DataTemplate. How can I achieve this?
I can't use ElementName, as the contextMenu isn't part of the visual tree
I can't use PlacementTarget, as this will give the UIElement produced by the DataTemplate
<Window x:Class="WpfApplication24.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ItemsControl ItemsSource="{Binding Data}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red">
<Border.ContextMenu>
<ContextMenu ItemsSource="{Binding <I want to bind to a property of MainWindow here>}"/>
</Border.ContextMenu>
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

You can have the window object in Tag of your Border and then can access it using PlacementTarget.Tag
<DataTemplate>
<Border Padding="5" CornerRadius="10" BorderThickness="1" BorderBrush="Red"
Tag="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType=Window}}">
<Border.ContextMenu>
<ContextMenu ItemsSource="{Binding PlacementTarget.Tag.PropertyName,
RelativeSource={RelativeSource Self}}"/>
</Border.ContextMenu>
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>

What I used is a simple custom control wrapper e.g. MyContextMenu
...with just one line of code, something like...
public class MyContextMenu : ContextMenu
{
public override void EndInit()
{
base.EndInit();
NameScope.SetNameScope(this, NameScope.GetNameScope(App.Current.MainWindow));
}
}
...and use that instead of ContextMenu.
That always 'scopes' to the MainWindow which may not always be optimal - but you can use ElementName etc.
2) The other option is using NameScope.NameScope="{StaticResource myNameScope}"
NameScope.NameScope seems like an optimal solution - however, you cannot bind from it (and it binds 'too late').
But you can use {StaticResource ...} - and you make a class which wraps around MainWindow's scope.
Similar, but I found the above 'less disruptive' (you can pretty much write the code you'd normally write).
For more details take a look at this answers (and for more ideas)...
ElementName Binding from MenuItem in ContextMenu
How to access a control from a ContextMenu menuitem via the visual tree?

Related

ItemsControl items bindings called when collapsed

I have an ItemsControl which displays a list of messages. It's defined as ...
<ItemsControl HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
ItemsSource="{Binding Messages}" >
</ItemsControl>
I then have a DataTemplate which handles the display for each message. It's defined as...
<DataTemplate DataType="{x:Type vm:MessageViewModel}">
<Button Command="{Binding CommandOpenPage}">
<Button.Template>
<ControlTemplate>
<Border Margin="2" BorderThickness="1"
BorderBrush="{Binding Flags, Converter={StaticResource msgFlagConverter}}"
Background="{Binding Flags, Converter={StaticResource msgFlagConverter}, ConverterParameter=1}" >
<TextBlock Text="{Binding Path=Message}" Style="{StaticResource ActionItem}" TextWrapping="Wrap" />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
Everything displays OK. My problem is when the parent controls are set to Visibility=Collapsed my ItemsControl still goes through the DataTemplate and calls the converters for BorderBrush and BackgroundBrush for each MessageViewModel.
This is bothersome because when the list is very large the bindings are set and converters are executed when they shouldn't. This list is only visible when the user chooses to see it. I understood the binding engine ignores elements under a collapsed parent. Is there an exception to this rule? Or am I just missing something?
I found my problem. The above ItemsControl and DataTemplate were in a UserControl. The visibility was originally handled inside the usercontrol itself by binding the main layout grid to a visibility property. By simply setting the user controls visibility in the parent XAML all bindings started behaving as expected.
This fixes my problem but I still don't understand the difference between setting the visibility of the main layout grid vs the visibility of the usercontrol itself.
<c:ApplicationMenuView Grid.Column="1" Grid.Row="4"
HorizontalAlignment="Left" Margin="1"
VerticalAlignment="Stretch"
DataContext="{Binding Menu}"
Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>

WPF: Set UserControl DataContext

I have the following MainWindow that lays out a left side navigation panel and a right side display area (both of these are UserControls).
Can someone explain how to assign the DataContext of the navigation panel (LinksView.xaml) to that of LinksViewModel.cs. I would like to bind a Command (BtnCompanyClickCommand) to the button and define BtnCompanyClickCommand in LinksViewModel.cs.
I have tried various methods that I found on StackOVerflow to set the DataContext but none of these solutions seem to work (binding RelativeSource, naming view and binding to name, etc.).
MainWindow.xaml
<StackPanel Orientation="Horizontal">
<vw:LinksView DataContext="{Binding RelativeSource={RelativeSource Self}}"/>
<ContentControl Content="{Binding CurrentUserControl}" />
</StackPanel>
LinksView.xaml
<StackPanel Orientation="Vertical">
<Button Content="Company" Width="75" Margin="3" Command="{Binding ElementName=Links,Path=BtnCompanyClickCommand}" />
</StackPanel>
FormsDictionary.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:SidekickAdmin.ViewModel"
xmlns:vw="clr-namespace:SidekickAdmin.View">
<DataTemplate DataType="{x:Type vm:CompanySummaryViewModel}">
<vw:CompanySummaryView>
<ContentControl Content="{Binding }" />
</vw:CompanySummaryView>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:LinksViewModel}">
<vw:LinksView />
</DataTemplate>
</ResourceDictionary>
EDIT
So I finally came across this explanation of how to set the DataContext of a UserControl which has to be done on the first child item of the UserControl.
Here is the modified LinksView.xaml that works.
<StackPanel Orientation="Vertical">
<StackPanel.DataContext>
<vm:LinksViewModel /> <!-- Bind the items in StackPanel to LinksViewModel -->
</StackPanel.DataContext>
<Button Content="Company" Width="75" Margin="3" Command="{Binding BtnCompanyClickCommand}" />
</StackPanel>
However, I am still not clear on why I have to set the DataContext of the child element and not the UserControl and why the DataTemplate for LinksView (set in FormsDictionary.xaml) doesn't tie into the DataContext of LinksViewModel. Any explanation would be appreciated.
First you have to refer to your DataContext (LinksViewModel.cs) in your XAML code.
You can do that either by directly instantiating it or use a ResourceDictionary. In the latter case you instantiate your DataConext either inside some .cs file or inside the ResourceDictionary .xaml file and store it in a named ResourceDictionary where you can find the reference later.
Second you simply have to associate the DataContext property of a View element like your LinksView.xaml with the corresponding DataContext.
This is pretty high-level and without any code but that's the basic idea behind it.
there should be an instance of LinksViewModel in MainWindowViewModel:
MainWindowViewModel.cs:
class MainWindowViewModel
{
public MainWindowViewModel()
{
LinksVM = new LinksViewModel();
}
public LinksViewModel LinksVM { get; private set; }
}
MainWindow.xaml
<StackPanel Orientation="Horizontal">
<vw:LinksView DataContext="{Binding LinksVM}"/>
<ContentControl Content="{Binding CurrentUserControl}" />
</StackPanel>
LinksView.xaml
<StackPanel Orientation="Vertical">
<Button Content="Company" Width="75" Margin="3" Command="{Binding BtnCompanyClickCommand}" />
</StackPanel>
since LinksView is explicitly created in MainWindow, there is no need in DataTemplate - it can be removed
<DataTemplate DataType="{x:Type vm:LinksViewModel}">
<vw:LinksView />
</DataTemplate>

How to show Master-Detail Informations in a collapsable ListView

I have a class that describes a certain task. This "task"-Class has a list of substeps.
What I wanted to do is to show these Informations in a ListView where the task-description should be used as the Groupheader and the substeps as the details
Also I wanted to be able to collapse and expand these groups.
Here is what I tried so far (simplified, but you'll get the idea hopefully):
public class Task : INotifyPropertyChanged
{
public string Description;
public ObservableCollection<String> substeps;
...
}
in the Viewmodel :
Task t = new Task();
t.Description = "Task1";
t.substeps.Add("substep 1");
t.substeps.Add("substep 2");
...
Tasks = new CollectionViewSource { Source = TaskList }; //TaskList is just a ObservableCollection<Task>
Tasks.GroupDescriptions.Add(new PropertyGroupDescription("Description"));
in xaml:
<s:SurfaceListBox Width="500" Height="1000" ItemsSource="{Binding TaskList.View}">
<s:SurfaceListBox.Resources>
<Style x:Key="ContainerStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Expander Header="{Binding Description}" IsExpanded="True">
<ItemsPresenter/>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</s:SurfaceListBox.Resources>
<s:SurfaceListBox.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource ContainerStyle}"/>
</s:SurfaceListBox.GroupStyle>
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding substeps}"/>
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
</s:SurfaceListBox>
The Result is a Listbox with my collapsed item. If I expand it, instead of each step I only see "(Listing)"
Do I have to build a class with the substeps and the description in it, and group by the description?
Try this:
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<ItemsControl ItemsSource={Binding substeps} />
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
Your problem is that the string binding to the ObservableCollection will just do a ToString() on that collection. You need iterate through the collection and display each item. By using the ItemsControl as I have done, you can also DataTemplate each subtask as you see fit.
ControlTemplate Binding
The Expander header binding will not work because it is inside a ControlTemplate which is inside the Style. The DataContext for the control template will not be your ViewModel but the control (i.e. SurfaceListBox) itself. Similar question is here.
There are two ways you can fix this.
1.Use DataTemplate
<s:SurfaceListBox.ItemTemplate>
<DataTemplate>
<Expander Header="{Binding Description}"
IsExpanded="True" >
<ItemsControl ItemsSource={Binding substeps} />
</Expander >
</DataTemplate>
</s:SurfaceListBox.ItemTemplate>
2.Use TemplatedParent binding
<Expander Header="{Binding Content.Description, , RelativeSource={RelativeSource TemplatedParent}}"
IsExpanded="True">
I personally recommend option 1.

UserControl's DataContext

I'm creating a UserControl I want to use something like this:
<controls:ColorWithText Color="Red" Text="Red color" />
So far, I've implemented similar controls like this:
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" >
<Border Width="15" Height="15" Background="{Binding Color, ElementName=ThisControl}" />
<TextBlock Text="{Binding Text, ElementName=ThisControl}" />
</StackPanel>
</UserControl>
where Color and Text are dependency properties of the control defined in code. This works, but specifying ElementName every time seems unnecessary.
Another option that works is using
<UserControl x:Class=… DataContext="{Binding ElementName=ThisControl}" Name="ThisControl">
and not specifying ElementNames, but that doesn't seem like a clean solution to me either.
I have two questions:
Why doesn't <UserControl DataContext="{RelativeSource Self}"> work?
What is the best way to do something like this?
For first one, try :
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
And for second question, I think using ElementName or AncestorBinding is best way to bind to UserControl's properties.
Why can't you use <UserControl DataContext="{RelativeSource Self}">?
This is how you would use the control
<Grid DataContext="{StaticResource ViewModel}">
<!-- Here we'd expect this control to be bound to -->
<!-- ColorToUse on our ViewModel resource -->
<controls:ColorWithText Color="{Binding ColorToUse}" />
</Grid>
Now because we've hardcoded our data-context in the control it will instead attempt to lookup ColorToUse property on the ColorWithText object not your ViewModel, which will obviously fail.
This is why you can't set the DataContext on the user control. Thanks to Brandur for making me understand that.
What is the best way to do something like this?
Instead you should set the DataContext in the first child UI element in your control.
In your case you want
<StackPanel
DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
Orientation="Horizontal" >
Now you have a DataContext which refers to your control so you can access any properties of that control using relative bindings.
I know this has been answered but none of the explanations give an Understanding of DataContext and how it works. This link does a great job for that.
EVERYTHING YOU WANTED TO KNOW ABOUT DATABINDING IN WPF, SILVERLIGHT AND WP7 (PART TWO)
In answer to your question #1
Why doesn't <UserControl DataContext="{RelativeSource Self}"> work?
This is a summary of the above link.
DataContext should not be set to Self at UserControl Element level. This is because it breaks the Inheritance of the DataContext. If you do set it to self and you place this control on a Window or another control, it will not inherit the Windows DataContext.
DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControls unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel. Put the DataContext binding here and bind it to the UserControl. This preserves the Inheritance.
See also this link below for a detailed explanation of this.
A SIMPLE PATTERN FOR CREATING RE-USEABLE USERCONTROLS IN WPF / SILVERLIGHT
In answer to your question #2
What is the best way to do something like this?
See code example below.
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" DataContext="{Binding ElementName=ThisControl}">
<Border Width="15" Height="15" Background="{Binding Color" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
Note that once you do this, you will not need the ElementName on each binding.
You should be using
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=Color}
for Databinding Related doubts always refer this sheet.
http://www.nbdtech.com/Blog/archive/2009/02/02/wpf-xaml-data-binding-cheat-sheet.aspx
You can set the datacontext to self at the constructor itself.
public ColorWithText()
{
InitializeComponent();
DataContext = this;
}
Now you can simply say
<UserControl x:Class="Namespace.ColorWithText" Name="ThisControl">
<StackPanel Orientation="Horizontal" >
<Border Width="15" Height="15" Background="{Binding Color}" />
<TextBlock Text="{Binding Text}" />
</StackPanel>
</UserControl>
For the desperate souls, who are trying to make pdross's answer work and can't:
It's missing an essential detail - Path=DataContext.
The lower code segment starts working when you add it there with this being the result:
<StackPanel DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext}">

Is there a way to group RadioButtons generated from the ItemTemplate of an ItemsControl

<DataTemplate x:Key="Genre_DataTemplate">
<RadioButton GroupName="One" Content="{Binding...
</DataTemplate>
Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree.
Any solution or workaround to group them together?. GroupName property also doesn't have any effect here.
[Update] I am trying this in Silverlight
The problem is that the RadioButton.GroupName behavior depends on the logical tree to find a common ancestor and effectively scope it's use to that part of the tree, but silverlight's ItemsControl doesn't maintain the logical tree. This means, in your example, the RadioButton's Parent property is always null
I built a simple attached behavior to fix this. It is available here: http://www.dragonshed.org/blog/2009/03/08/radiobuttons-in-a-datatemplate-in-silverlight/
I think the problem is somewhere else in the control tree. Can you post more details?
Here is a sample xaml code that works as expected:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&lang=en-us&format=rss_200">
<XmlDataProvider.XmlNamespaceManager>
<XmlNamespaceMappingCollection>
<XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/>
</XmlNamespaceMappingCollection>
</XmlDataProvider.XmlNamespaceManager>
</XmlDataProvider>
<DataTemplate x:Key="itemTemplate">
<RadioButton GroupName="One">
<Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/#url}"/>
</RadioButton>
</DataTemplate>
<ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}">
<WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
</ControlTemplate>
</Grid.Resources>
<ItemsControl
Width="375"
ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}"
ItemTemplate="{StaticResource itemTemplate}"
Template="{StaticResource controlTemplate}">
</ItemsControl>
</Grid>
</Page>
P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)

Resources