Binding ToolTip in UserControl - wpf

I tried to bind a ToolTip text in a UserControl this way:
<Grid.ToolTip>
<TextBlock
Text="{
Binding Path=InfoTT,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}" />
</Grid.ToolTip>
And it doesn't work, the Tooltip was empty and in logs, I saw:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.UserControl', AncestorLevel='1''. BindingExpression:Path=InfoTT; DataItem=null; target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')*
But when I did:
<Grid
ToolTip="{
Binding Path=InfoTT,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}">
</Grid>
It worked. Can anyone explain why the first way doesn't work?

When Binding.RelativeSource doesn't resolve, you can always be sure that the Binding.Target is not part of the visual tree.
In your first example you are explicitly defining the tree structure of the ToolTip. You are explicitly creating the content e.g. by adding the TextBlock. The content of the ToolTip is not part of the visual tree and therefore the Binding.RelativeSource can't be resolved.
In your second example, you let the FrameworkElement implicitly create the ToolTip content.
Now FrameWorkElement will first resolve the Binding, which resolves, as the FrameworkElement is still part of the visual tree. The resolved value is taken, ToString invoked, a TextBlock created and the string value assigned to TextBlock.Text.
Solution
To solve the binding problem, when implementing the ToolTip explicitly, you can implement a Binding Proxy as suggested in a comment by #Mark Feldman which makes use of the StaticResource markup to provide a Binding.Source to elements that are not part of the visual tree.
It's basically a bindable ObjectDataProvider.
A similar solution to the binding proxy is to define the content as a resource of the Grid and then reference it via DynamicResource using a ContentPresnter:
<UserControl>
<Grid>
<Grid.Resources>
<!-- The proxy -->
<TextBlock x:Key="ToolTipText"
Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=InfoTT}" />
<Grid.ToolTip>
<ToolTip>
<ContentPresenter Content="{DynamicResource ToolTipText}" />
</ToolTip>
</Grid.ToolTip>
</Grid>
</UserControl>
But you could also make use of the fact that the DataContext is still inherited. Bindings to the DataContext will still resolve.
In your scenario, where you want to bind the content of the ToolTip to a property of the parent UserControl, you could bind this property to a property of the view model, which is the current DataContext of Grid (and therefore for its ToolTip). I only recommend this, when binding to business data and not layout data:
<UserControl InfoTT="{Binding ViewModelInfoTT}">
<UserControl.DataContext>
<ViewModel />
</UserControl.DataContext>
<Grid>
<Grid.ToolTip>
<ToolTip>
<TextBlock Text="{Binding ViewModelInfoTT}" />
</ToolTip>
</Grid.ToolTip>
</Grid>
</UserControl>
If you don't use view models and host the data directly in the control, you may like to set the DataContext to the control itself. This way you simplify all bindings and of course can now bind to the UserControl from within the ToolTip:
// Constructor
public MyUserControl()
{
InitializeComponent();
// Set the UserControl's DataContext to the control itself
this.DataContext = this;
}
<UserControl>
<Grid>
<Grid.ToolTip>
<ToolTip>
<TextBlock Text="{Binding InfoTT}" />
</ToolTip>
</Grid.ToolTip>
</Grid>
</UserControl>
Alternatively override the DataContext. Of course you'll lose access to the current context:
<UserControl>
<Grid DataContext="{Binding RelativeSource={RelativeSource AncestoType=UserControl}>
<Grid.ToolTip>
<ToolTip>
<TextBlock Text="{Binding InfoTT}" />
</ToolTip>
</Grid.ToolTip>
</Grid>
</UserControl>

Related

How to identify the DataContext of different items in .xaml?

I have a FilterUserControl with FilterViewModel to be its DataContext.
In FilterControl.xaml:
<Button x:Name="FilterButton">
<Button.ContextMenu PlacementTarget="{x:Reference FilterButton}" ItemsSource="{Binding FilterConditions}" Style="{StaticResource ButtonContextMenu}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<MenuItem Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu, Mode=FindAncestor}, Path=DataContext.ChangeFilterCondition}"
CommandParameter="{Binding}">
...
I searched on Web and knew that
CommandParameter="{Binding}"
is the same as
CommandParameter="{Binding DataContext,RelativeSource={RelativeSource Self}}"
I originally thought that DataContext would be FilterViewModel But after debugging I found that DataContext was actually "each item of FilterConditions"
I finally got the evidence here ItemsSource vs DataContext in binding case
Now I would like to know in .xaml how do we identify what the DataContext is? What are the typical/common cases? Thanks.
Long story short: In an ItemsControl with an assigned ItemsSource you can be sure that each item has a different DataContext, this means ItemTemplate and ItemContainerStyle. Not the ItemsPanel.
DataContext is the root of binding path, and it remains the same throughout XAML hierarchy unless you change it.
You can change the DataContext explicitly or by changing the ItemsSource. Having an ItemsSource changes the DataContext of each element, so you don't have to take care of indexes.
This is not true when you assign to Items because it implicitly adds them to the ItemCollection and clears ItemsSource. Using Items is similar to when you add items to any other control. i.e. the contents of the DataContext in this case:
<ItemsControl>
<Button Content="{Binding A}"/>
</ItemsControl>
is just like this case:
<StackPanel>
<Button Content="{Binding A}"/>
</StackPanel>
or even:
<Button>
<Button Content="{Binding A}"/>
</Button>
However using ItemsSource means that you're asking the ItemsControl to enumerate through the given collection, take each element, set their DataContext and render them. Therefore the DataContext is changed there.
RelativeSource Self resolves to the current XAML element, so these two are equal:
<... Prop="{Binding Path=Width, RelativeSource={RelativeSource Self}}"/>
<... Prop="{Binding Path=Width, ElementName=name}" x:Name="name"/>
DataContext is always the root object of the binding ({Binding} or {Binding Path=.}), so these three are equal:
<... Prop="{Binding Path=A}"/>
<... Prop="{Binding Path=DataContext.A, RelativeSource={RelativeSource Self}}"/>
<... Prop="{Binding Path=DataContext.A, ElementName=name}" x:Name="name"/>
Default Binding Path of all the objects in the object tree always resolves to the same object (unless they are changed). e.g. If grid.DataContext=A then A is the Binding root for all the objects inside grid object tree hierarchically.
Note that, you can either change DataContext in the code (preferably in the view's constructor), or you can "bind" the DataContext to have different scopes, so that this view:
<Grid DataContext="{Binding}"> // this is redundant and points to VM
<Grid DataContext="{Binding Child1}">
<Button Command="{Binding Action11}"/>
<Button Command="{Binding Action12}"/>
</Grid>
<Grid DataContext="{Binding Child2}">
<Button Command="{Binding Action21}"/>
<Button Command="{Binding Action22}"/>
</Grid>
<ItemsControl ItemsSource="{Binding Collection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button
DataContext="{Binding}" // this is redundant and points to an item
Command="{Binding ElementAction}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
perfectly represents this VM:
VM
Child1
Action11
Action12
Child2
Action21
Action22
Collection
Item1
ElementAction
Item2
ElementAction
Item3
ElementAction
...
There's only one case for an itemscontrol ( or things inherit from itemscontrol ).
https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.itemscontrol?view=netcore-3.1
When you bind itemssource to a collection.
What happens is each item in that collection is presented.
Datatemplating then gives an instance of whatever UI you specified in the template.
That row UI appears in your itemscontrol itemspanel.
The row UI has a datacontext of the item.
You can use a datatemplate selector or datatemplates associated with datatype so that you get different UI.
You can change the itemspanel that presents these so it's say a canvas instead of the default stackpanel.
But whatever you do, the datacontext of each will be one of those items in the collection you bound to itemssource.

Change DataContext of specific property inside control - WPF

I have User control which contains TextBox with WaterMark inside
<AdornerDecorator>
<TextBox
Height="20"
Margin="10,0"
Grid.Column="0"
Text="{Binding MainCategoryTextBoxValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Name="MainCatTextBox">
<controls:WatermarkService.Watermark>
<TextBlock VerticalAlignment="Center" x:Name="MainCategoryTextBlock"> </TextBlock>
</controls:WatermarkService.Watermark>
</TextBox>
</AdornerDecorator>
You can see here WatermarkService implementation
https://stackoverflow.com/a/836463/1548347
I want take "MainCategoryTextBlock" textblock inside <controls:WatermarkService.Watermark> and set it DataContext to be same like my UserControl DataContext in order to change Watermark text in RunTime from my ViewModel.
I tried to bind "MainCategoryTextBlock" DataContext with RelativeSource to my UserControl DataContext but I didn`t succeed (maybe syntax error - Im not sure).
DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
Do you have any clue how can I solve it?
Thanks
If your UserControl has a name then you can do it like this:
DataContext={Binding ElementName="YourUserControlName", Path=DataContext}
But i can see that you are using your textbox inside an adorner decorator so you can't use FindAncestor in this case because your textbox and your UserControl won't belong to the same visual tree.
You should be setting the data context property of your window to your view model, and bind the text property of your textblock to your view model property.
<TextBlock Text={Binding Path=PropertyOnViewModel} />

WPF bind usercontrol's property to parent's property

I have created a usercontrol, which has 2 dependency properties. I want to bind those dependency properties to the mainViewModel's property, so that whenever something gets changed in the user-control the parent's property gets updated.
I tried, binding it normally but it didn't work. How can I bind the user-control's DP to the parent's property.
I tried this:
UC:
<TextBox Name="TextBox" Text="{Binding ElementName=UCName, Path=DP1, Mode=TwoWay}"/>
MainWindow:
<UCName:UCName Width="330" CredentialName="{Binding Path=DP1, Mode=TwoWay}"></UCName:UCName>
Thanks
For binding to the parent's properties you should use RelativeSource in your Binding. Like this:
<TextBox Name="TextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UCName:UCName}}, Path=DP1, Mode=TwoWay}"/>
Details: RelativeSource Markup Extension
Note: Don't forget define namespace UCName.
Something like this:
<MainWindow DataContext="mainViewModel">
<local:TestControl ucDependProp="{Binding viewModelProp}/>
</MainWindow>
className: TestControl.xaml
<UserControl Name="thisControl">
<TextBox Text="{Binding ElementName=thisControl, Path=ucDependProp}/>
</UserControl>
The user control shouldn't be aware of the parent view model.

Binding parent container props to content child control in Silverlight

Example:
<UserControl x:Name="userControl"
<StackPanel x:Name="container" Margin="0">
<TextBox Text="{Binding Path=SettingValue, RelativeSource={RelativeSource Mode=Self}}"/>
</StackPanel>
</UserControl>
UserControl contains SettingValue dependency property, TextBox doesn't,
so this example won't work.
I could've done this if I had AncestorType, like in WPF:
RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControlType}
Is there any possibility to bind to UserControl.SettingValue property?
Did you try the following? Use the ElementName source (the syntax might be a bit off).
<TextBox Text="{Binding Path=SettingValue, ElementName=userControl"/>
The answer I've found here:
Binding Silverlight UserControl custom properties to its' elements

WPF Treeview contextmenu IsChecked binding MVVM

I've got a TreeView to which I associate a ContextMenu. That contextmenu has an item whose IsChecked property I want to bind to my ViewModel. Since I am using a tree each treeitem is bound to a subproperty of my ViewModel.
In the VS2010 output window I am seeing this databinding error:
BindingExpression path error: 'IsAutoStart' property not found on 'object' ''HostMgmtViewModel' (HashCode=12565727)'. BindingExpression:Path=IsAutoStart; DataItem='HostMgmtViewModel'
This clearly shows it is trying to bind to my ViewModel and not to the treeitem's associated data. How do I bind to the correct object? Remember my contextmenu is associated with the whole TreeView not to the specific treeitem.
---------- Edit
As xandy pointed out below the resolution to my problem was to bind the IsChecked like this:
{Binding Path=PlacementTarget.SelectedItem.IsDisabledStart, Mode=OneWay, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}
<TreeView Name="tview" Grid.Row="0" Tag="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}">
<TreeView.ContextMenu>
<ContextMenu>
<MenuItem Name="miC" Header="{Binding Path=Tag.Key}" DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"></MenuItem>
</ContextMenu>
</TreeView.ContextMenu>
</TreeView>
This is the working code snippet I have. Courtesy of [this].1 All you need is to change the binding path in the tag. I am currently binding the Treeview to a dictionary, so it is the Key property of it. It should not have any problem in binding to any object collections. One interesting finding is context menu is not in part of element tree and this cause the problem. I could bind the text box with no problem:
<TextBlock Grid.Row="1" DataContext="{Binding ElementName=tview, Path=SelectedItem}">
<TextBlock.Text>
<Binding Path="Key" />
</TextBlock.Text>
</TextBlock>
But it is not functioning if for menuitem if I put the same thing.

Resources