How can I use an ElementName binding within a ControlTemplate? - wpf

I have multiple TextBlocks which reference different elements in my application. My code works fine when used directly in the page. However, I want to create a ControlTemplate and a ContentControl to reduce the duplication of code.
How can I pass a reference to an ElementName into the ControlTemplate from the ContentControl using TemplateBinding? The following code throws this error:
"Cannot convert the value in attribute 'ElementName' to object of type
'System.String'. Object of type
'System.Windows.TemplateBindingExpression' cannot be converted to type
'System.String'. "
In addition to the Tag attribute, I have tried ContentStringFormat which also did not work.
What is the correct method to get this to work using templates?
Thanks in advance for your help,
--- Shawn
Here is the code sample:
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Page.Resources>
<ControlTemplate x:Key="MyTemplate" TargetType="{x:Type ContentControl}">
<TextBlock Margin="{Binding ElementName={TemplateBinding Tag}, Path=Margin}" Text="{TemplateBinding Content}" TextAlignment="{Binding ElementName={TemplateBinding Tag}, Path=TextAlignment}" Width="{Binding ElementName={TemplateBinding Tag}, Path=Width}" />
</ControlTemplate>
</Page.Resources>
<StackPanel>
<TextBlock x:Name="AnotherElement" Margin="10" Text="Main TextBlock" TextAlignment="Center" Width="100" />
<TextBlock x:Name="AnotherElement2" Margin="20" Text="Second TextBlock" TextAlignment="Left" Width="250" />
<TextBlock Margin="{Binding ElementName=AnotherElement, Path=Margin}" Text="Here is my TextBlock!" TextAlignment="{Binding ElementName=AnotherElement, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement, Path=Width}" />
<TextBlock Margin="{Binding ElementName=AnotherElement2, Path=Margin}" Text="Here is my Second TextBlock!" TextAlignment="{Binding ElementName=AnotherElement2, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement2, Path=Width}" />
<ContentControl Content="Hello!" Tag="AnotherElement" Template="{StaticResource MyTemplate}" />
<ContentControl Content="Hello Again!" Tag="AnotherElement2" Template="{StaticResource MyTemplate}" />
</StackPanel>
</Page>

This seems like a funny way to template something, but it can be done, you just have to get a bit fancy with your bindings.
The below will work, but I still dont think this is a good way to template a control
Bind the TextBlock Tag to the actual Element, then in the ControlTemplate bind Tag to Tag and use the values from there as Tag is the Element, you can use any element from it.
<Page.Resources>
<ControlTemplate x:Key="MyTemplate" TargetType="{x:Type ContentControl}">
<TextBlock Name="_this" Tag="{TemplateBinding Tag}" Margin="{Binding ElementName=_this, Path=Tag.Margin}" Text="{TemplateBinding Content}" TextAlignment="{Binding ElementName=_this, Path=Tag.TextAlignment}" Width="{Binding ElementName=_this, Path=Tag.Width}" />
</ControlTemplate>
</Page.Resources>
<StackPanel>
<TextBlock x:Name="AnotherElement" Margin="10" Text="Main TextBlock" TextAlignment="Center" Width="100" />
<TextBlock x:Name="AnotherElement2" Margin="20" Text="Second TextBlock" TextAlignment="Left" Width="250" />
<TextBlock Margin="{Binding ElementName=AnotherElement, Path=Margin}" Text="Here is my TextBlock!" TextAlignment="{Binding ElementName=AnotherElement, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement, Path=Width}" />
<TextBlock Margin="{Binding ElementName=AnotherElement2, Path=Margin}" Text="Here is my Second TextBlock!" TextAlignment="{Binding ElementName=AnotherElement2, Path=TextAlignment}" TextTrimming="CharacterEllipsis" Width="{Binding ElementName=AnotherElement2, Path=Width}" />
<ContentControl Content="Hello!" Tag="{Binding ElementName=AnotherElement}" Template="{StaticResource MyTemplate}" />
<ContentControl Content="Hello Again!" Tag="{Binding ElementName=AnotherElement2}" Template="{StaticResource MyTemplate}" />
</StackPanel>

Related

Modifying TabControl's header

So I'm adding my views directly to the TabControl's Items collection at runtime (instead of creating TabItems around them and addings those TabItems to TabControl). The views expose a property (wrapper around a ViewModel property of the same name) named HasChanges that I want to bind to TabItem's Header to show a Asterisk (*) sign to identify tabs with unsaved changes, just like VS does. I have already tried using DataTemplates but am having trouble accessing the view object in the DataTemplate. What's the correct way of doing this? Here's one of my several attempts:
<TabControl.ItemTemplate>
<DataTemplate DataType="UserControl">
<StackPanel Orientation="Horizontal" Margin="0" Height="22">
<TextBlock VerticalAlignment="Center" Text="{Binding HeaderText, RelativeSource={RelativeSource AncestorType=UserControl}}" />
<TextBlock Text="*" Visibility="{Binding HasChanges, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource B2VConverter}}" />
</StackPanel>
</DataTemplate>
</TabControl.ItemTemplate>
Note that I'm trying two different binding methods for the two TextBlocks, none of which is working. My views inherit from UserControl and expose properties HasChanges and HeaderText.
OK. I solved it myself. For anyone else trying to implement a VS-like Close button and unsaved changes asterisk, here's the template:
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="HeaderTemplate" >
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0" Height="22">
<TextBlock VerticalAlignment="Center" Text="{Binding RelativeSource={RelativeSource AncestorType=TabItem}, Path=Content.HeaderText}" />
<TextBlock Text=" *" ToolTip="Has unsaved changes" Visibility="{Binding Content.DataContext.HasChanges, RelativeSource={RelativeSource AncestorType=TabItem}, Converter={StaticResource B2VConverter}}" />
<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Width="18" Height="18"
Margin="6,0,0,0" Padding="0" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" HorizontalAlignment="Center"
Command="{Binding DataContext.TabClosingCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}"
VerticalAlignment="Center" Focusable="False">
<Grid Margin="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Line StrokeThickness="3" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Stroke="Gray" X1="1" Y1="1" X2="9" Y2="9" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Line StrokeThickness="3" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Stroke="Gray" X1="1" Y1="9" X2="9" Y2="1" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</Button>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
Results in an elegant drawing-based button with a flat-look. Your View must implement Boolean HasChanges and HeaderText properties, plus you need to define a BooleanToVisibilityConverter in your resources section, named B2VConverter.

How can I wrap a custom text?

I have a listbox that uses datatemplates and one of the elements in the template is a textblock. Problem is that the words won't wrap, and I don't want to set a fixed size. Anybody that knows how to resolve this problem? It's driving me crazy!
<ListBox Grid.Row=" 1" HorizontalContentAlignment="Stretch" Background="#24221f" ItemsSource="{Binding Messages}" ScrollViewer.VerticalScrollBarVisibility="Visible" ClipToBounds="False" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate >
<Border BorderBrush="#24221f" BorderThickness="3" Width=" auto">
<DockPanel Background="{StaticResource blackBackground}" HorizontalAlignment="Stretch" Width="auto">
<Border BorderThickness="3" BorderBrush="Transparent">
<Image Source="{Binding IconImageUrl}" VerticalAlignment="top" Height="22" Width ="22" DockPanel.Dock="Left" />
</Border>
<Border BorderThickness="3" BorderBrush="LightGray" Height="auto" Width="auto" HorizontalAlignment="Left" VerticalAlignment="Center" DockPanel.Dock="Left">
<Image Source="{Binding ProfileImageUrl}" VerticalAlignment="Top" HorizontalAlignment="Left" Height="48" Width ="48" />
</Border>
<StackPanel Orientation="Vertical" DockPanel.Dock="Left" Margin="5,0,0,0">
<Label Content="{Binding Path=Sender}" Foreground="#feb41c" FontFamily="Verdana" FontWeight="Bold" FontSize="14" />
<TextBlock Width="100" Text="{Binding Path=ShortMessage}" Margin="10,0,0,0" Foreground="BlanchedAlmond" TextWrapping="Wrap" FontFamily="Verdana" />
<Label Content="{Binding Path=Time}" Margin="10,0,0,0" Foreground="DarkGray" FontFamily="Verdana" FontStyle="Italic"/>
</StackPanel>
</DockPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
StackPanel is Evil :=) when i have strange behaviours in a xaml which include StackPanel, switching to a Grid with right parameters ( fixed sized, or stars or "Auto" ) often fix the issue.
Note also that there is an error in your xaml since you set the DockPanel.Dock of your first image (IconImageUrl) whereas it is in the border that surrrounds it that you should be setting it. That may get the Layout to do strange things.
just try with HorizontalContentAlignment property to "Stretch" of ListBoxItems using the Style
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
and also disable the HorizontalScrollBar visibility
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
Update
<Window.Resources>
<SolidColorBrush x:Key="blackBackground" Color="Black"/>
<Style TargetType="{x:Type ListBoxItem}" >
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</Window.Resources>
<Grid>
<ListBox Grid.Row=" 1" HorizontalContentAlignment="Stretch" Background="#24221f" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding Messages}" ScrollViewer.VerticalScrollBarVisibility="Visible" ClipToBounds="False" BorderBrush="{x:Null}">
<ListBox.ItemTemplate>
<DataTemplate >
<Border BorderBrush="#24221f" BorderThickness="3" Width=" auto">
<DockPanel Background="{StaticResource blackBackground}" HorizontalAlignment="Stretch" Width="auto">
<Border BorderThickness="3" BorderBrush="Transparent">
<Image Source="{Binding IconImageUrl}" VerticalAlignment="top" Height="22" Width ="22" DockPanel.Dock="Left" />
</Border>
<Border BorderThickness="3" BorderBrush="LightGray" Height="auto" Width="auto" HorizontalAlignment="Left" VerticalAlignment="Center" DockPanel.Dock="Left">
<Image Source="{Binding ProfileImageUrl}" VerticalAlignment="Top" HorizontalAlignment="Left" Height="48" Width ="48" />
</Border>
<StackPanel Orientation="Vertical" DockPanel.Dock="Left" Margin="5,0,0,0">
<Label Content="{Binding Path=Sender}" Foreground="#feb41c" FontFamily="Verdana" FontWeight="Bold" FontSize="14" />
<TextBlock Text="{Binding Path=ShortMessage}" Margin="10,0,0,0" Foreground="BlanchedAlmond" TextWrapping="Wrap" FontFamily="Verdana" />
<Label Content="{Binding Path=Time}" Margin="10,0,0,0" Foreground="DarkGray" FontFamily="Verdana" FontStyle="Italic"/>
</StackPanel>
</DockPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
I think this thread answer's your question, see the accespted answer by "Nash" - Force TextBlock to wrap in WPF ListBox
( and remember to upvote the answer the the linked thread if it helps you :) )

Can I use a DataTemplate for toolbar buttons and still make the name meaningful?

I have a Toolbar whose ItemSource is a collection of toolbarItems which contain the bitmap text and other info for the button and the xaml includes a DataTemplate to bind the data to the button.
Our app now needs to become 508 compliant and when I run the Accessible Event Watcher it is listing all the toolbar button names as "Unknown".
Can someone tell me how to provide a meaningful name to the buttons?
Here's the portion of xaml applying to this issue:
<ToolBar.ItemTemplate>
<DataTemplate DataType="{x:Type src:toolBarItem}">
<DataTemplate.Resources>
<src:toolBarItemConverter x:Key="buttonConverter" />
<src:booleanToVisibilityConverter x:Key="boolToVisibilityConverter" />
<src:toolBarButtonFormatConverter x:Key="toolBarFormatDisplayConverter" />
<src:stringToVisibilityConverter x:Key="stringToVisibilityDisplayConverter" />
</DataTemplate.Resources>
<StackPanel Orientation="Horizontal">
<Border Style="{StaticResource SeparatorStyle}" Visibility="{Binding menuSeparator, Converter={StaticResource boolToVisibilityConverter}}"/>
<Button x:Name="listButton" Height="{Binding menuHeight, Mode=OneWay}" Width="{Binding menuWidth}" VerticalAlignment="Top" HorizontalAlignment="Center" Visibility="{Binding isActiveButton, Converter={StaticResource boolToVisibilityConverter}}" Tag="{Binding}"
ToolTip="{Binding menuTooltip}" IsEnabled="{Binding isEnabled}" >
<UniformGrid VerticalAlignment="Center" HorizontalAlignment="Center" Rows="{Binding menuText,Converter={StaticResource toolBarFormatDisplayConverter}}" >
<!-- button image -->
<Image Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Source="{Binding menuImage, Converter={StaticResource buttonConverter}}"/>
<!-- button name -->
<Viewbox StretchDirection="DownOnly" HorizontalAlignment="Center" VerticalAlignment="Bottom" Visibility="{Binding menuText, Converter={StaticResource stringToVisibilityDisplayConverter}}" >
<TextBlock x:Name="buttonName" FontFamily="Segoe UI" Width="{Binding menuWidth}" FontSize="12" Grid.Row="1" TextAlignment="Center" TextWrapping="Wrap" HorizontalAlignment="Center" VerticalAlignment="Bottom" Text="{Binding menuText}" Foreground="Black" />
</Viewbox>
</UniformGrid>
<!-- </StackPanel> -->
</Button>
</StackPanel>
</DataTemplate>
</ToolBar.ItemTemplate>
Thanks,
Ron
OK we figured this out. Need to simply bind your names to the AutomationProperties.Name
<Button x:Name="listButton" AutomationProperties.Name="{Binding menuText}"
Height="{Binding menuHeight, Mode=OneWay}" Width="{Binding menuWidth}"
VerticalAlignment="Top" HorizontalAlignment="Center"
Visibility="{Binding isActiveButton,
Converter={StaticResource boolToVisibilityConverter}}"
Tag="{Binding}" ToolTip="{Binding menuTooltip}" IsEnabled="{Binding isEnabled}" >

Why must I move a Popup outside of a control to have databinding work?

I have this XAML:
<ContentControl Micro:View.Model="{Binding ChildViewModel}">
<Popup x:Name="TestPopup" Placement="Mouse" AllowsTransparency="True">
<Border x:Name="border" Background="White" Padding="5" CornerRadius="10" BorderThickness="2" BorderBrush="Black" >
<StackPanel Orientation="Vertical">
<TextBlock x:Name="MainInfos" Text="{Binding MainInfos}" />
<TextBlock x:Name="AltInfos" Text="{Binding AltInfos}" />
<TextBlock x:Name="OtherInfos" Text="{Binding OtherInfos}" />
<TextBlock x:Name="CanNotUseFieldInfos" Foreground="Red" Text="{Binding CanNotUseFieldInfos}" />
</StackPanel>
</Border>
</Popup>
</ContentControl>
When I update the values of the properties of the datacontext, the textblocks are not updated.
If I move Popup outside of ContentControl like so:
<Popup x:Name="TestPopup" Placement="Mouse" AllowsTransparency="True">
<Border x:Name="border" Background="White" Padding="5" CornerRadius="10" BorderThickness="2" BorderBrush="Black" >
<StackPanel Orientation="Vertical">
<TextBlock x:Name="MainInfos" Text="{Binding MainInfos}" />
<TextBlock x:Name="AltInfos" Text="{Binding AltInfos}" />
<TextBlock x:Name="OtherInfos" Text="{Binding OtherInfos}" />
<TextBlock x:Name="CanNotUseFieldInfos" Foreground="Red" Text="{Binding CanNotUseFieldInfos}" />
</StackPanel>
</Border>
</Popup>
<ContentControl Micro:View.Model="{Binding ChildViewModel}" PreviewMouseMove="Canvas_PreviewMouseMove" MouseEnter="myCanvas_MouseEnter" MouseLeave="myCanvas_MouseLeave" d:LayoutOverrides="Width, Margin" />
It works.
Could someone explain me why? Is it possible to make the first XAML work?
Thanks in advance
Cannot reproduce any weird behavior from just wrapping a Popup in a ContentControl, i suspect the Micro:View.Model attached property changes the DataContext of the ContentControl.

Wpf Bind View to ViewModel add to wpf window

I have a view that contains a ItemsControl with some textblocks inside to display the name and other information. in my window I am adding the view to the window as follows and in the code behind of the window i am binding the datacontext of the view to the view model in the MainWindow Loaded event as follows ViewOwnerSideBar.DataContext = viewModel The application compiles but when I run it I dont get data? I checked my viewmodel and I do have data in my collection that I am returning. Does anyone have any good examples of how to do this. I am going to have a sidebar view and a main view on the right displaying the details of the owner.
This is my View
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/ColorsAndBrushes.xaml"/>
<ResourceDictionary Source="/Resources/DefaultStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<DockPanel >
<ScrollViewer VerticalScrollBarVisibility="Auto" >
<ItemsControl Width="250"
VerticalAlignment="Stretch"
BorderThickness="0"
ItemsSource="{Binding Path=AllOwners}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="2">
<Border Margin="2 2 0 0"
CornerRadius="4"
Background="Gray"
Opacity=".5" />
<Border BorderBrush="{StaticResource redBrush}"
BorderThickness="2"
CornerRadius="4"
Background="White"
Margin="0 0 2 2"
Padding="3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.ColumnSpan="2"
FontWeight="Bold"
Text="{Binding FullName}" />
<TextBlock Grid.Row="1"
Text=" FirstName: " />
<TextBlock Grid.Row="1"
Grid.Column="1"
Text="{Binding FirstName}" />
<TextBlock Grid.Row="2"
Text=" Email: " />
<TextBlock Grid.Row="2"
Grid.Column="1"
Text="{Binding Email}" />
</Grid>
</Border>
<Button Style="{StaticResource openButton}" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</DockPanel>
This is my window
<DockPanel>
<v:HeaderTopBar DockPanel.Dock="Top"></v:HeaderTopBar>
<!--<uc:SearchBar DockPanel.Dock="Top" />-->
<StatusBar DockPanel.Dock="Bottom">
<StatusBarItem DockPanel.Dock="Right">
<Slider x:Name="zoomSlider"
Width="125"
Value="1"
Minimum=".5"
Maximum="2" />
</StatusBarItem>
<StatusBarItem DockPanel.Dock="Right">
<TextBlock>Zoom:</TextBlock>
</StatusBarItem>
<StatusBarItem>
<TextBlock Text="{Binding StatusText}" />
</StatusBarItem>
</StatusBar>
<Expander DockPanel.Dock="Left"
ExpandDirection="Right"
IsExpanded="True"
BorderThickness="0 1 1 1"
BorderBrush="Gray"
Margin="0 2 0 0"
Padding="2">
<Expander.Header>
<TextBlock Text="Contacts"
FontSize="14"
FontWeight="Bold">
<TextBlock.LayoutTransform>
<RotateTransform Angle="90" />
</TextBlock.LayoutTransform>
</TextBlock>
</Expander.Header>
<v:OwnerSideBar/>
</Expander>
<TabControl x:Name="tabs"
Grid.Column="2"
Margin="5 0">
<TabControl.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=zoomSlider,
Path=Value}"
ScaleY="{Binding ElementName=zoomSlider,
Path=Value}" />
</TabControl.LayoutTransform>
</TabControl>
</DockPanel>
Firstly, ensure that the AllOwners collection you are binding to is an ObservableCollection.
Also, check the Output window in Visual Studio when executing, look for First chance exceptions being caught. This will be a clue as to where your binding problem will be.
I like to put a textblock on the View bound to the Items.Count property on the ItemsControl so that you can see if it is binding and not rendering anything or not binding correctly.
Give the ItemsControl a name, then put a textblock in:
<TextBlock Text="{Binding ElementName=itemControl1,Path=Items.Count}/>
This might be something you already looked at, but you might have a binding typo, did you check your output window to see if you get any trace messages?
And I guess I'm blind but I don't see where your usercontrol is in the xaml of the second entry.

Resources