WPF Dynamic Resource Not Updating when inside data template - wpf

I am trying to setup a system in a WPF app where the user can select a different theme and the UI updates. To achieve this I am removing one resource dictionary and merging in another one.
Everything is working fine except one scenario.
I have some pages that define a datatemplate. In the datatemplate is a rectangle that is bound to a string property on the viewmodel (using Caliburn.Micro) and I have a converter that converts the string into a drawingbrush (it finds it from the resources).
The problem is that the dynamicresource in the drawingbrush (the color) will not update.
Every other instance of rectangle I have bound the same way (not in a datatemplate) the color of the drawing brush updates perfectly. Only when inside the datatemplate does this problem occur.
Here is a sample of the data template on a view
<DataTemplate x:Key="ListBoxItemTemplate">
<Border Style="{DynamicResource EntitySelectListBox}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Rectangle Grid.Column="0" Fill="{Binding IconName, Converter={converters:StringToResourceConverter}}" Width="50" Height="50" Margin="5" ToolTip="{Binding ToolTip}" />
<TextBlock FontFamily="Segoe WP"
FontWeight="Light"
FontSize="22"
Grid.Column="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="{Binding ButtonText}" />
</Grid>
</Border>
</DataTemplate>
Here is an example of a drawing brush that has a dynamicresource for the color:
<DrawingBrush x:Key="BankIcon" Viewbox="0,0,442,442" ViewboxUnits="Absolute">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="9.20833333333333,0,0,9.20833333333333,0,0"/>
</DrawingGroup.Transform>
<DrawingGroup>
<DrawingGroup.Transform>
<MatrixTransform Matrix="1,0,0,1,0,2.04885336170188"/>
</DrawingGroup.Transform>
<GeometryDrawing Brush="{DynamicResource SecondaryText}" Geometry="M32.015748,33.342608 L46.283901,33.342608 C47.231779,33.342608 48,34.111116 48,35.061416 L48,40.968297 29.109026,40.968297 C31.057581,39.645195 32.207827,37.567466 32.207827,35.105579 32.207827,34.463728 32.135616,33.879828 32.015748,33.342608 z M1.7188548,33.342608 L21.193252,33.342608 C21.734045,33.580305 22.220392,33.759667 22.584643,33.892346 24.90359,34.727827 24.90359,35.253493 24.90359,35.449457 24.90359,35.986481 23.92294,36.182345 23.261798,36.182345 21.415607,36.182345 19.949486,35.468384 19.243114,35.041909 L17.321123,33.889921 15.507445,40.263165 16.585441,40.951892 0,40.968297 0,35.061416 C8.7927075E-13,34.111116 0.76985754,33.342608 1.7188548,33.342608 z M22.790523,18.230994 L25.366021,18.230994 25.366021,21.121156 C27.345029,21.183175 28.700861,21.687368 29.703128,22.191564 L28.856339,25.079107 C28.100782,24.702539 26.716707,23.982205 24.582318,23.982205 22.381153,23.982205 21.594926,25.110746 21.594926,26.179891 21.594926,27.467599 22.72608,28.221998 25.431822,29.259503 28.949705,30.578852 30.489161,32.27603 30.489161,35.105438 30.489161,37.771993 28.636319,40.099727 25.209281,40.667104 L25.209281,43.902294 22.602338,43.902294 22.602338,40.855485 C20.623328,40.792207 18.644319,40.22619 17.510837,39.502072 L18.362478,36.519611 C19.618635,37.270223 21.344919,37.898937 23.261813,37.898937 25.271298,37.898937 26.620819,36.927818 26.620819,35.449302 26.620819,34.003588 25.522762,33.125251 23.167186,32.27603 19.901545,31.081883 17.733186,29.541929 17.733186,26.651183 17.733186,23.9494 19.618635,21.844013 22.790523,21.279064 z M40.239403,16.937238 L44.995147,16.937238 44.995147,31.067614 40.239403,31.067614 z M32.794241,16.937238 L37.545128,16.937238 37.545128,31.067614 32.794241,31.067614 z M10.453898,16.937238 L15.205758,16.937238 15.205758,31.067614 10.453898,31.067614 z M3.0077641,16.937238 L7.7625359,16.937238 7.7625359,31.067614 3.0077641,31.067614 z M23.952052,0 L24.047946,0.0024883747 C24.709093,0.017653378 25.175256,0.11243361 26.113014,0.68999864 L48,14.939825 24.047946,14.939825 23.952052,14.939825 0,14.939825 21.885821,0.68999864 C22.824745,0.11243361 23.292458,0.017653378 23.952052,0.0024883747 z"/>
</DrawingGroup>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
Here is a resource dictionary that imports a couple other resource dictionarys. One for styles and one for the vectoricons (they are shared between the skins).
ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="SixtenLabs.CashFlow.Client.Skins.Monochrome">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Resources/CommonStyles.xaml"/>
<ResourceDictionary Source="/Resources/VectorIcons.xaml"/>
I have tried moving various parts around to different places (app.xaml, window.resources) to no avail. Any ideas would be appreciated.
Thanks.

Try turning off virtualization in your ListBox as you may be recycling containers and the containers wont allways honour changes in DynamicResource bindings.
<ListBox VirtualizingStackPanel.IsVirtualizing="False"
VirtualizingStackPanel.VirtualizationMode="Standard" />

Related

DrawingImage icon gets automatically trimmed when stretch=uniform

We use vector icons exported from Expression Design in our application, but I just noticed that all empty space in the icons gets trimmed away when they are displayed inside a stretched Image. Since the whole point of having vector icons is to allow them to stretch and scale nicely, this seems very strange.
Here is an example. Both the red and the blue star are designed in a 32 pixels wide document, but the blue star is much smaller. Setting the stretch property to Uniform suddenly makes the two icons the same size.
Is it possible to solve this and keep the whitespace around the icons? I guess a possible workaround would be to add a transparent background rectangle that covers the whole icon area, but this seems like a bad solution to me.
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="GeneralTest.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Window.Resources>
<DrawingImage x:Key="small_blue_star">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Blue" Geometry="F1 M 20.4989,22C 20.4634,22.0177 16.2771,19.0022 16.2416,19.0022C 16.2061,19.0022 12.0021,22.0177 11.9844,22C 11.9489,21.9823 13.4921,17.0332 13.4744,16.9977C 13.4744,16.9623 9.4655,14.0354 9.48323,13.9999C 9.48323,13.9644 14.45,14.0177 14.4855,13.9999C 14.5032,13.9822 16.2061,8.99765 16.2416,8.99765C 16.2771,8.99765 17.9623,13.9822 17.98,13.9999C 18.0155,14.0177 22.9823,13.9644 23,13.9999C 23,14.0354 18.9911,16.9623 18.9911,16.9977C 18.9734,17.0332 20.5166,21.9823 20.4989,22 Z "/>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
<DrawingImage x:Key="big_red_star">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Red" Geometry="F1 M 26.0781,32C 25.9941,32.0436 16.0823,24.6277 15.9983,24.6277C 15.9143,24.6277 5.96055,32.0436 5.91855,32C 5.83455,31.9564 9.48848,19.7856 9.44648,19.6983C 9.44648,19.6111 -0.0453207,12.4133 -0.00332647,12.326C -0.00332647,12.2388 11.7564,12.3697 11.8404,12.326C 11.8824,12.2824 15.9143,0.0243702 15.9983,0.0243702C 16.0823,0.0243702 20.0723,12.2824 20.1142,12.326C 20.1982,12.3697 31.958,12.2388 32,12.326C 32,12.4133 22.5082,19.6111 22.5082,19.6983C 22.4662,19.7856 26.1201,31.9564 26.0781,32 Z "/>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Window.Resources>
<StackPanel x:Name="LayoutRoot">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Stretch=None" Width="100"/>
<Image Source="{StaticResource big_red_star}" Width="32" Stretch="None"/>
<Image Source="{StaticResource small_blue_star}" Width="32" Stretch="None"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Stretch=Uniform" Width="100"/>
<Image Source="{StaticResource big_red_star}" Width="32" Stretch="Uniform" />
<Image Source="{StaticResource small_blue_star}" Width="32" Stretch="Uniform"/>
</StackPanel>
</StackPanel>
</Window>

TabControl DataTemplate Instance Creation Issues

I have a WPF issue that I don't understand - can anyone help?
The WPF below is used as the ContentTemplate for a standard TabControl and resides within a ResourceDictionary. MyElementItemsControl is a simple derivative of ItemsControl and MyDesignCanvas is a simple derivative of Canvas.
<DataTemplate x:Key="TabContent" x:Shared="False">
<Grid>
<Grid Grid.RowSpan="2">
<ScrollViewer x:Name="contentScrollViewer" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" >
<Grid>
<View:MyElementItemsControl BorderBrush="Transparent" x:Name="schedulePanel" ItemsSource="{Binding Path=Elements}" Background="White">
<View:MyElementItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<View:MyDesignCanvas Height="1000" Width="1000" HorizontalAlignment="Left" VerticalAlignment="Top"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
Background="Transparent">
</View:MyDesignCanvas>
</ItemsPanelTemplate>
</View:MyElementItemsControl.ItemsPanel>
</View:MyElementItemsControl>
<Grid.LayoutTransform>
<TransformGroup>
<ScaleTransform>
<ScaleTransform.ScaleX>
<Binding ElementName="SlideZoom" Path="Value" Mode="OneWay"/>
</ScaleTransform.ScaleX>
<ScaleTransform.ScaleY>
<Binding ElementName="SlideZoom" Path="Value" Mode="OneWay"/>
</ScaleTransform.ScaleY>
</ScaleTransform>
</TransformGroup>
</Grid.LayoutTransform>
</Grid>
</ScrollViewer>
</Grid>
<Slider Opacity="0.5" VerticalAlignment="Top" HorizontalAlignment="Left" Width="300" Grid.Row="1" Name="SlideZoom" Orientation="Horizontal" Minimum="0.1" Maximum="3" Value="1">
</Slider>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
</Grid>
</DataTemplate>
When I run the code I get two issues I don't understand:
I seem to only get a single ScrollViewer when I would expect a ScrollViewer per item. So if I add two tab items and make the canvas different sizes, the scroll bars are adjusted to the size of the biggest canvas only. I expected that the Shared=False attribute would create new instances of the template for each tab.
Maybe related to item 1 - if I stick a breakpoint on the constructor of MyDesignCanvas it gets hit when the first tab is added but not when other tabs are added. Only when I start closing tabs does the breakpoint get hit again - I would expect a hit on each tab addition.
I guess I don't really understand data templating enough, so can anyone explain what might be going on or point me at some resources that may help me diagnose this?
Thanks
I've realised what the issue is - the WPF TabControl does internal virtualization of tab content, so has been re-using the tab contents and just changing the data context despite me using Shared=False. See this SO question and this one too for more details.

DataContext issues with ListBox after changes to MainWindow.xaml

I am new to WPF and the MVVM design pattern this month, and more than a little out of practice in general. To learn, I've been playing around with textboxes, rectangles, and ways to display them in a window. I began with Ashley Davis' excellent "Simple Drag Selection in WPF" tutorial, which walks through creating a view model for a collection of rectangles, binding a listbox to said collection, and styling the listbox with a canvas, creating a data template for the rectangles, as well as basic "rubber band" selection logic.
I have since built on this tutorial to improve the drag selection so that it behaves much more like selection does in windows explorer, and to allow resizing the rectangles from the corners or edges.
All was well until I changed the MainWindow.xaml in an effort to include a column on the side for various buttons and controls, thus moving the "editor surface" grid from inside a 1x1 grid on the main window to a column of a 1x2 grid, moving the data template to the grid's resources (since it will be the only element in the window that needs it). As soon as I did this, subroutines that I wrote which interact with the listbox started misbehaving--rubber band selection no longer works. There's no visual indication that listbox items are being selected (they were highlighted previously), and interrogating listBox.SelectedItems.Count after a drag-selection mouseUp event returns a zero.
After some experimentation, reading many questions on this site and sections of my WPF Unleashed book, and going over the msdn databinding overview, as of this morning I still cannot find my mistake(s). I believe it is a data binding mistake or incorrect data context.
Some details about the view models involved:
DataFieldViewModel
...implements INotifyPropertyChanged and exposes properties for its (in this case a rectangle and a textbox) X,Y position, width, height, visibility, and selection status (a way to track it across several rubber band selection operations)
PageViewModel
...implements INotifyPropertyChanged, and has among other things an ObservableCollection of type DataFieldViewModel, called DataFields, and exposes it as a ReadOnly Property.
Here's a look at MainWindow.xaml.vb and one of the broken subs:
Namespace EditorUI
'
' The main window of the editor.
'
Partial Public Class MainWindow
Inherits Window
'
' Temporary. Will be replaced with a collection of pages eventually
'
Private Pages As PageViewModel
(remaining data members and properties snipped for brevity)
Public Sub New()
InitializeComponent()
Pages = New PageViewModel
End Sub
(and here's one of the subs with issues)
'
' Select all the data fields that intersect the selection rectangle.
' Remove any selected data fields which do not.
'
Private Sub ApplyDragSelectionRectangle()
If (LeftMouseDrag) Then
Dim selectionRectangle As New Rect(Canvas.GetLeft(selectionRectangleBorder), _
Canvas.GetTop(selectionRectangleBorder), _
selectionRectangleBorder.Width, _
selectionRectangleBorder.Height)
'
' Find and select all the list box items.
'
For Each dataFieldViewModel As DataFieldViewModel In Me.Pages.GetDataFields
Dim hitBox As New Rect(dataFieldViewModel.hbX, _
dataFieldViewModel.hbY, _
dataFieldViewModel.hbWidth, _
dataFieldViewModel.hbHeight)
If (selectionRectangle.IntersectsWith(hitBox)) Then
If (dataFieldViewModel.ExistingSelection) Then
'
' data field is already part of an existing selection; unselect it
'
Me.DataFieldListBox.SelectedItems.Remove(dataFieldViewModel)
Else
Me.DataFieldListBox.SelectedItems.Add(dataFieldViewModel)
End If
End If
If Not (selectionRectangle.IntersectsWith(hitBox)) Then
If (dataFieldViewModel.ExistingSelection) Then
'
' data field was part of an existing selection; reselect it
'
Me.DataFieldListBox.SelectedItems.Add(dataFieldViewModel)
Else
Me.DataFieldListBox.SelectedItems.Remove(dataFieldViewModel)
End If
End If
Next
Else
dragSelectionCanvas.Visibility = Visibility.Collapsed
'
' update all data fields' existing selection status to the new
' selection (first set them all to false to catch data fields
' that were removed)
'
For Each dataFieldViewModel As DataFieldViewModel In Me.DataFieldListBox.Items
dataFieldViewModel.ExistingSelection = False
Next
For Each dataFieldViewModel As DataFieldViewModel In Me.DataFieldListBox.SelectedItems
dataFieldViewModel.ExistingSelection = True
Next
End If
End Sub
Finally, here is the XAML in its entirety:
<Window x:Class="EditorUI.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Editor_UI_Experiments.EditorUI"
Title="Editor UI Experiments"
Width="900"
Height="600"
Loaded="Window_Loaded"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="778*" />
</Grid.ColumnDefinitions>
<Button
Grid.Column="0"
VerticalAlignment="Top"
Height="25"
Content="Explode :D"
Name="Button1"
/>
<Grid
Name="EditorSurface"
Grid.Column="1"
MouseDown="Editor_MouseDown"
MouseUp="Editor_MouseUp"
MouseMove="Editor_MouseMove"
>
<Grid.Background>
<ImageBrush ImageSource="{Binding GetPageImage}" />
</Grid.Background>
<Grid.DataContext>
<local:PageViewModel/>
</Grid.DataContext>
<Grid.Resources>
<!--
A data template that defines the visuals for a data field.
-->
<DataTemplate
DataType="{x:Type local:DataFieldViewModel}"
>
<!--
The data field is embedded in a Grid so that we can set the Margin
The margin is set so that the ListBox item selection fits nicely around the Rectangle.
-->
<Grid
Margin="0,2,2,2"
>
<!--
text box where the data field's response lives (it could be a Database tag,
or a check mark, or custom response)
-->
<TextBox
Width="{Binding Width}"
Height="{Binding Height}"
Background="LightBlue"
Cursor="IBeam"
MouseDown="TextBox_MouseDown"
MouseUp="TextBox_MouseUp"
MouseMove="TextBox_MouseMove"
Text="Example Text"
/>
<!--
rectangle that lives on top of the text field to aid in positioning the data field
-->
<Rectangle
Width="{Binding Width}"
Height="{Binding Height}"
Stroke="LightBlue"
StrokeThickness="5"
Fill="White"
Opacity="0.5"
Cursor="SizeAll"
MouseDown="Rectangle_MouseDown"
MouseUp="Rectangle_MouseUp"
MouseMove="Rectangle_MouseMove"
Visibility="{Binding Visibility}"
/>
<!--
Thumb "handles" to give the user a way to resize the data field
-->
<!--
These four live in the corners of a data field and allow resizing on
X and Y simultaneously
-->
<Rectangle
Width="7"
Height="7"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="-1,-1,0,0"
Cursor="SizeNWSE"
Fill="LightGray"
Stroke="Gray"
Opacity="0.6"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Width="7"
Height="7"
VerticalAlignment="Top"
HorizontalAlignment="Right"
Margin="0,-1,-1,0"
Cursor="SizeNESW"
Fill="LightGray"
Stroke="Gray"
Opacity="0.6"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Width="7"
Height="7"
VerticalAlignment="Bottom"
HorizontalAlignment="Left"
Margin="-1,0,0,-1"
Cursor="SizeNESW"
Fill="LightGray"
Stroke="Gray"
Opacity="0.6"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Width="7"
Height="7"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Margin="0,0,-1,-1"
Cursor="SizeNWSE"
Fill="LightGray"
Stroke="Gray"
Opacity="0.6"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<!--
These four live along the data field's edges and allow resizing in the X
or Y direction only. They have zero opacity to avoid visual clutter
-->
<Rectangle
Height="5"
VerticalAlignment="Top"
HorizontalAlignment="Stretch"
Margin="7,0,7,0"
Cursor="SizeNS"
Fill="Yellow"
Opacity="0"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Height="5"
VerticalAlignment="Bottom"
HorizontalAlignment="Stretch"
Margin="7,0,7,0"
Cursor="SizeNS"
Fill="Yellow"
Opacity="0"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Width="5"
VerticalAlignment="Stretch"
HorizontalAlignment="Left"
Margin="0,7,0,7"
Cursor="SizeWE"
Fill="Yellow"
Opacity="0"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
<Rectangle
Width="5"
VerticalAlignment="Stretch"
HorizontalAlignment="Right"
Margin="0,7,0,7"
Cursor="SizeWE"
Fill="Yellow"
Opacity="0"
Visibility="{Binding Visibility}"
MouseDown="Thumb_MouseDown"
MouseUp="Thumb_MouseUp"
MouseMove="Thumb_MouseMove"
/>
</Grid>
</DataTemplate>
</Grid.Resources>
<!--
This ListBox presents the data fields
The data template that defines the visuals for each data field is in the
resources section at the start of this file.
-->
<ListBox
x:Name="DataFieldListBox"
ItemsSource="{Binding GetDataFields}"
SelectionMode="Extended"
Background="Transparent"
>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style
TargetType="ListBoxItem"
>
<Setter
Property="Canvas.Left"
Value="{Binding X}"
/>
<Setter
Property="Canvas.Top"
Value="{Binding Y}"
/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<!--
Render a drag selection rectangle using a Canvas with a border
-->
<Canvas
x:Name="dragSelectionCanvas"
Visibility="Collapsed"
>
<Border
x:Name="selectionRectangleBorder"
BorderBrush="Blue"
BorderThickness="1"
Background="LightBlue"
CornerRadius="1"
Opacity="0.5"
/>
</Canvas>
</Grid>
</Grid>
I'm sure my code is riddled with novice mistakes, but it's been fun so far. Hope to improve quickly and maybe turn this into something useful. Feedback and insight are most welcome. If someone happens to find where I'm going wrong, you'll have my gratitude.
-Tom
I suspect it has something to do with the fact you are defining the Grid's DataContext in the XAML, but your drag event is referencing an object in the code-behind. So your ListBox is binding to the XAML copy of PageViewModel, while your code-behind is working with a different copy of PageViewModel
I'd suggest removing the DataContext property from the XAML and instead setting it in the code-behind, such as Me.DataContext = Pages
Just keep in mind that its usually bad practice to be setting the DataContext in code-behind unless it's the application startup code.

Preventing deformation in XAML Grid's background when resizing

I am writing a brush in XAML that I can use to paint the background of a Grid to create a banner. It looks like this:
I want the brush to "stretch" with the Grid when the Window resizes, but I do not want the center angles to deform.
I only need to be able to draw the shapes in the background of a Grid. How can I avoid the deformation?
The code I've written looks like this:
<Window x:Class="WpfApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="60" Width="300">
<Window.Resources>
<DrawingBrush x:Key="GridBackground">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Geometry="M0,1 0,0 0.4,0 0.45,0.5 0.4,1Z" Brush="#FF6A00" />
<GeometryDrawing Geometry="M0.6,1 0.55,0.5 0.6,0 1,0 1,1Z" Brush="#FF0000" />
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Window.Resources>
<Grid Background="{StaticResource GridBackground}">
<TextBlock Foreground="White" VerticalAlignment="Center">Some text</TextBlock>
</Grid>
</Window>
I would make it two brushes, one anchored to the right, and one anchored to the left. Something like this:
<Grid>
<GeometryXXX Geometry="M0,1 0,0 0.4,0 0.45,0.5 0.4,1Z" Width="300" HorizontalAlignment="Left" Brush="#FF6A00">
<GeometryXXX Geometry="M0,1 0,0 0.4,0 0.45,0.5 0.4,1Z" Width="300" HorizontalAlignment="Right" Brush="#FF0000">
<TextBlock Foreground="White" VerticalAlignment="Center">Some text</TextBlock>
</Grid>
I don't have my compiler open, and I don't remember the name of the Geometry drawing object.
The other way of doing it would be to create a valueconverter, and do something like:
...
<GeometryDrawing Geometry="{Binding Width, ValueConverter=LeftAngledThing}" Brush="#FF6A00" />
<GeometryDrawing Geometry="{Binding Width, ValueConverter=LeftAngledThing}" Brush="#FF0000" />
...
You would need to look up the exact syntax for how to do this though, as I don't remember it right now.

Silverlight: Applying datacontext to an element within a style

I have defined a style in app.xaml. This style contains several text TextBlocks which I would like to controle as I apply the style to an object, in this case a UserPin.
How can I access these TextBlocks runtime?
I get the style by:
Style = Application.Current.Resources["UserPin"] as Style;
The style looks like this:
<Style x:Name="UserPin" TargetType="RRML_UserControls:UserPin" >
<Setter Property="RenderTransformOrigin" Value="0.5,0.5" />
<Setter Property="AnchorPoint" Value="0.5,0.5" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RRML_UserControls:UserPin">
<Grid Height="71.969" Width="Auto">
<Grid.RenderTransform>
<ScaleTransform x:Name="PART_PinScale" />
</Grid.RenderTransform>
<Grid.RowDefinitions>
<RowDefinition Height="29"/>
<RowDefinition Height="16"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.247*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="0.753*"/>
</Grid.ColumnDefinitions>
<Image Height="Auto" Source="Resources/Users.png" x:Name="PART_imgUser" VerticalAlignment="Top" Stretch="Uniform" Margin="0,0,0,0" Grid.Column="1">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform/>
<TranslateTransform/>
</TransformGroup>
</Image.RenderTransform>
</Image>
<TextBlock HorizontalAlignment="Center" Margin="0,0,0,0" Width="Auto" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="1" TextWrapping="Wrap" VerticalAlignment="Center" TextAlignment="Center" x:Name="txtBottom" Text="{Binding Mode=OneWay, Path=LocationName}">
<TextBlock.DataContext>
<RRML_RRMLServiceReference:Location LocationName="Initial Name"/>
</TextBlock.DataContext>
</TextBlock>
<TextBlock HorizontalAlignment="Right" Margin="0,0,0,0" VerticalAlignment="Center" Text="L" TextWrapping="Wrap"/>
<TextBlock Margin="0,0,0,0" Text="R" TextWrapping="Wrap" d:LayoutOverrides="Width, Height" Grid.Column="2" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The TextBlock value I'm trying to set is txtBottom.
As you can see I have tried to apply a datacontext and a databinding to the field. This works, but all objects get the value "Initial Name" of course.
My questions are:
how can I apply my datacontext so txtBottom.Text changes, or
how can I change the value of the TextBlock named txtBottom without databinding?
in short can I access these fields or properties at all?
Runtime :)
So far I have found that Triggers may be used only in WPF.
I think of something like this:
var styledobject = new NiceObject();
styledobject.Style = Application.Current.Resources["UserPin"] as Style;
styledobject.DataContext = locationData;
Where locationData is my object containing data.
If anyone wonders; I am placing icons on a map and want to name them.
You should not explicitly apply DataContext on the TextBlock. DataContext is inherited by child FrameworkElements. You should try to set data context explicitly as little and as high up the Visual Tree as possible (for your own sanity's sake :-))
If this is a custom control, you can override on the OnApplyTemplate method and use the GetTemplateChild(string name) to retrieve references to named elements within your control.
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
TextBlock txtBottom = GetTemplateChild("txtBottom") as TextBlock;
}
Externally, if you must, you can imperatively access that specific control at runtime using an extension method to traverse the Visual Tree to find it by name.
public static T FindChild<T>(this DependencyObject element, string name)
where T : FrameworkElement
{
//Code to find the control
}

Resources