WPF shared property - wpf

I have a question which I guess it's some basic knowledge which I missing in WPF.
I set default width (generix.XML) to Textbox with some Minim width for the textbox
<Style TargetType="{x:Type TextBox}">
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="MinWidth" Value="50"/>
</Style>
I have two deferent controls which holds text box. Both Textboxes has same width..
I which to add some property to one of the controls which will declare the width of the textbox, and will override its width declaration, in a way that the textbox will 'find' to this property.
here is some drawing describes my requirement:
Update:
I just figure out that I didn't described one more importing thing.
I Have some DataTemplate which uses the textbox. As I wrote above, I have two controls which have the same DataType (MyData) I also created DateTemplate to display MyData. I would like that each control will display the textbox (from the datatemple) with different width.
update 2:
here is some more code
1- The dataTemplate to my data where is using textbox
<DataTemplate DataType="{x:Type ml:MyData}">
<Border BorderBrush="Transparent" ClipToBounds="True" Style="{StaticResource errorBorder}">
<TextBox Text="{Binding MyText}"/>
</Border>
</DataTemplate>
2- the way I used the datatemplate which uses the Textbox.
<ContentPresenter Grid.Column="1" Margin="10,1,10,1" HorizontalAlignment="Left" Content="{Binding}" />
This contentPresentor is been displayed in two diffrent controls. and as I wrote before, I would like that each control will display the textbox in diferent width
It's look like I miss some basic knloage (attached proerty? logic/visual tree?).
Thanks, Leon

Good question, the main idea in DataTemplate is that you have specific graphical representation for some data. You can read more about it in MSDN.
If you want to customize your TextBox, and have it different properties inside different UserControls, you might want to use ControlTemplate.
The thing is that if you want to control properties of specific control (in this case TextBox with some border) you should use ControlTemplate.
Your XAML should look something like:
<ControlTemplate TargetType="{x:Type TextBox}">
<--! define the ControlTemplate here with some Width property-->
<ControlTemplate>
and the Control which use it will have TextBox (as you defined it, with Border):
<TextBox Grid.Column="1" Margin="10,1,10,1" HorizontalAlignment="Left" Content="{Binding}" Width="50"/>

Related

What's the difference between ItemTemplate and ItemContainerStyle in a WPF ListBox?

In WPF Listbox, I'm confused with these 2 notions:
ItemTemplate and ItemContainerStyle
Can someone explain me more?
The ItemTemplate is for styling how the content of your data item appears. You use it to bind data fields, format display strings, and so forth. It determines how the data is presented.
The ItemContainerStyle is for styling the container of the data item. In a list box, this would be a ListBoxItem. Styling here affects things like selection behavior or background color. It determines style and UX of the display.
The MSDN page for ItemContainerStyle, linked above, has a pretty good example showing some differences:
<!--Use the ItemTemplate to set a DataTemplate to define
the visualization of the data objects. This DataTemplate
specifies that each data object appears with the Proriity
and TaskName on top of a silver ellipse.-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="TextBlock">
<Setter Property="FontSize" Value="18"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</DataTemplate.Resources>
<Grid>
<Ellipse Fill="Silver"/>
<StackPanel>
<TextBlock Margin="3,3,3,0"
Text="{Binding Path=Priority}"/>
<TextBlock Margin="3,0,3,7"
Text="{Binding Path=TaskName}"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<!--Use the ItemContainerStyle property to specify the appearance
of the element that contains the data. This ItemContainerStyle
gives each item container a margin and a width. There is also
a trigger that sets a tooltip that shows the description of
the data object when the mouse hovers over the item container.-->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Control.Width" Value="100"/>
<Setter Property="Control.Margin" Value="5"/>
<Style.Triggers>
<Trigger Property="Control.IsMouseOver" Value="True">
<Setter Property="Control.ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=Content.Description}"/>
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.ItemContainerStyle>
The ItemContainerStyle just a wrapper for the DataTemplate so that a common item style can be applied to different data layouts.
Also, from this answer to "DataTemplate vs ItemContainerStyle":
You can do all your styling in the ItemTemplate but the ItemContentStyle has VisualStates which control the Opacity on mouse over/disabled/selected etc.
If you want to change those opacity state changes, or if you want any Container shape other than a rectangle, like a triangle for example, then you'll have to override the default ItemContainerStyle.

How to define all textblock elements the same color

We are using global styles definitions for most of the types. We define then in the app.xaml file. When using TextBlock it is a problem to define a foreground color because it changes all the controls using TextBlock (Button's content color for example).
How can we define a global style which will act only on specific TextBlock usages?
current problematic usage:
<Style TargetType={x:Type TextBlock}>
<Setter Property="Foreground" Value="Red"/>
</Style>
Since I don't think there is a way to differentiate “your” TextBlocks and those that are part of other controls, your options are quite limited.
You could create named Style and add Style="{StaticResource coloredTextBlock}" or Foreground="{StaticResource textBlockColor}" to all TextBlocks. This would be quite tedious and non-DRY.
You could create your own type that inherits from TextBlock and style that. This has some of the disadvantages of the above solution (you have to remember doing that). But it has much less repetition.
This is because ContentPresenter creates a TextBlock for a string content, and since that TextBlock isn't in the visual tree, it will lookup to Application level resource. And if you define a style for TextBlock at Application level, then it will be applied to these TextBlock within ControlControls.
A workaround is to define a DataTemplate for System.String, where we can explicitly use a default TextBlock to display the content. You can place that DataTemplate in the same dictionary you define the TextBlock style so that this DataTemplate will be applied to whatever ContentPresenter effected by your style.
Add this to your Application resources and it should work for you -
<DataTemplate DataType="{x:Type system:String}">
<TextBlock Text="{Binding}">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}"/>
</TextBlock.Resources>
</TextBlock>
</DataTemplate>
Declare a namespace in your xaml, if not referred already -
xmlns:system="clr-namespace:System;assembly=mscorlib"
EDIT : Check this sample where its working..
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Red"/>
</Style>
<DataTemplate DataType="{x:Type system:String}">
<TextBlock Text="{Binding}">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}"/>
</TextBlock.Resources>
</TextBlock>
</DataTemplate>
<Style TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Yellow"/>
</Style>
<Style TargetType="{x:Type Label}">
<Setter Property="Foreground" Value="Blue"/>
</Style>
Just provide a x:key in the style, like:
<Style x:Key="stRedTextBlock" TargetType={x:Type TextBlock}>
<Setter Property="Foreground" Value="Red"/>
</Style>
and mention the key in the TextBlock control style, where ever you require this particular TextBlock style, like:
<TextBlock Name="textBlock1" Style="{StaticResource stRedTextBlock}" />

Styling a Textblock autogenerated in a ContentPresenter

As I saw, a lot of people ran into this exact problem but I can't understand why my case is not working and it is starting to drive me crazy.
Context: I have a DataGrid which is to be colored according to the values of each cell. Hence, I have a dynamic style resolving the actual template to be used for each cell. Backgrounds now work accordingly.
New problem: when I have a dark background, I want the font color to be white and the font weight to be bold so the text is correctly readable. And... I can't style it correctly.
I read some Stackoverflow posts about that:
This one fits my problem but doesn't provide me any working solution
This one is also clear and detail but... duh
This is almost the same problem as me but... Solution does not work
Here is what I tried so far:
<!-- Green template-->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ContentPresenter.Resources>
<Style BasedOn="{StaticResource BoldCellStyle}" TargetType="{x:Type TextBlock}" />
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
</ControlTemplate>
Does not work. Background is green, but text stays in black & not bold.
BTW, the BoldCellStyle is as easy as it can be:
<Style x:Key="BoldCellStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="White" />
</Style>
Okay. Second try (which is a real stupid one but well...)
<!-- Green template -->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ContentPresenter.Resources>
<Style x:Key="BoldCellStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="White" />
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
</ControlTemplate>
Doesn't work either.
Then, I tried to play with the ContentPresenter's properties:
<!-- Green template -->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter TextElement.FontWeight="Bold" TextElement.Foreground="White" TextBlock.Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
And... As you can expect, this does not even work.
Intrigued, I used Snoop to browse all the components of my interface.
In the first two cases, Snoop actually shows me that each cell is a Grid with a ContentPresenter containing a TextBlock and the actual Style but... The TextBlock's properties do not apply and FontWeight is still normal.
Last case, even more shocking, I can see that snoop shows me that we actually have a ContentPresenter with the right properties (ie TextElement.FontWeight="Bold"), but the autogenerated TextBlock under is - still - not styled.
I can't get what am I missing here. I tried as you can see almost all I could possibly do here, and the TextBlocks keep being non-formatted.
Any idea here? Thanks again!
The DataGridColumns that derive from DataGridBoundColumn (all except DataGridTemplateColumn) has a property ElementStyle that is applied to the TextBlock when it is created. For e.g. DataGridTextColumn It looks like this
static DataGridTextColumn()
{
ElementStyleProperty.OverrideMetadata(typeof(DataGridTextColumn),
new FrameworkPropertyMetadata(DefaultElementStyle));
// ...
}
It overrides the metadata for ElementStyle and provides a new default value, DefaultElementStyle, which basically just sets the default margin for the TextBlock.
public static Style DefaultElementStyle
{
get
{
if (_defaultElementStyle == null)
{
Style style = new Style(typeof(TextBlock));
// Use the same margin used on the TextBox to provide space for the caret
style.Setters.Add(new Setter(TextBlock.MarginProperty, new Thickness(2.0, 0.0, 2.0, 0.0)));
style.Seal();
_defaultElementStyle = style;
}
return _defaultElementStyle;
}
}
This style is set in code everytime a new DataGridCell is created with element.Style = style; and this is overriding the Style you are trying to set, even if you try to set it implicitly.
As far as I know, you'll have to repeat this for your columns
<DataGridTextColumn Header="Column 1" ElementStyle="{StaticResource BoldCellStyle}" .../>
<DataGridTextColumn Header="Column 2" ElementStyle="{StaticResource BoldCellStyle}" .../>

WPF DataGrid Hyperlink Appearance and Behaviour

I am quite new to WPF, there is so much to learn and I think I'm getting there, slowly. I have a DataGrid which is used for display and user input, it's quite a tricky Grid as it is the main focus of the entire application. I have some columns that are read-only and I have used a CellStyle Setter to set KeyboardNavigation.IsTabStop to False to keep user input focused on the important columns and that works fine. I would like a couple of the read-only columns to be hyperlinks that show a tooltip and do not receive the focus, however I am struggling to write the XAML that will achieve all three requirements at the same time.
One of the columns is to indicate if the item on the row has any Notes. I have used the following XAML to display a HasNotes property in the cell in a DataGridTemplateColumn and on the Tooltip show the actual notes, in the Notes property:
<DataGridTemplateColumn x:Name="NotesColumn" Header="Notes">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding HasNotes, Mode=OneWay}">
<TextBlock.ToolTip>
<TextBlock Text="{Binding Notes}" MaxWidth="300" TextWrapping="Wrap" />
</TextBlock.ToolTip>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellStyle>
<Style>
<Setter Property="KeyboardNavigation.IsTabStop" Value="False"/>
</Style>
</DataGridTemplateColumn.CellStyle>
</DataGridTemplateColumn>
That works fine but I would like to make it a Hyperlink instead so the user can do something with the Notes when they click on the cell contents.
I have another column which is a DataGridHyperlinkColumn used to display a Unit of Measurement on a hyperlink and when clicked the user can change the unit. (The reason I have done it like this, rather than a ComboBox for example, is because as much as I want the user to be able to change the unit I want to make the interface such that it is a very deliberate act to change the unit, not something that can be done accidentally). The following XAML puts the Hyperlink column on for Unit
<DataGridHyperlinkColumn x:Name="ResultUnitLink" Binding="{Binding Path=Unit.Code}" Header="Unit" Width="Auto" IsReadOnly="True">
<DataGridHyperlinkColumn.CellStyle>
<Style>
<Setter Property="KeyboardNavigation.IsTabStop" Value="False"/>
</Style>
</DataGridHyperlinkColumn.CellStyle>
<DataGridHyperlinkColumn.ElementStyle>
<Style>
<EventSetter Event="Hyperlink.Click" Handler="ChangeUnit" />
</Style>
</DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>
One problem with the XAML for the Hyperlink column is that the IsTabStop = False doesn't appear to work, when tabbing through the Grid my hyperlink column still receives the focus, unlike the other columns where I've used a setter to change IsTabStop. If push comes to shove I could live with that but I'd rather not.
What I actually want from both those columns is an amalgamation of the two appearances/behaviours i.e. Columns where the data is displayed on a hyperlink, where TabStop = False and which display a tooltip of a different property when hovered over.
Can anyone help advise me how to get a column that achieves the following:
Hyperlink displaying one property
Tooltip displaying a different property
IsTabStop = False that actually works when used with a hyperlink
Thanks in advance to anyone who can help.
I've had issues with the Hyperlink in the past, so have this Style which I use for Labels or Buttons to make them look like Hyperlinks. Try making your column Template into a Button or a Label and applying this style.
<Style x:Key="ButtonAsLinkStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ContentPresenter ContentStringFormat="{TemplateBinding ContentStringFormat}" />
</TextBlock>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Blue" />
<Setter Property="Cursor" Value="Hand" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>

Wrapped Rows with Silverlight DataGrid

I'm trying to style a Silverlight DataGrid so that the content displayed in the grid wraps. I want each grid row (and the grid header), to consist of TWO lines of cells, instead of one. This makes each row taller, but keeps all of the content visible on screen simultaneously, instead of having to scroll horizontally to see all of the fields. Here is a picture to help illustrate what I am going for:
Screenshot
(I don't have enough rep to post an image directly but the link above will show you an example screen shot)
I see the templates that let me customize how the different cells are styled, but I'm not seeing anything that will let me to control how those cells are displayed beside each other on the screen.
Your best bet here is going to be to abandon the datagrid and use a ListView instead, and inside the ListView you will want to show a UserControl of your own design. I did something similar for an application I built.
In your XAML for your ListView you will want to set the ItemContainerStyle and inside that you'll want to display your custom UserControl (in which you can use a Grid to setup the rows/colums and their spans). It basically looks like this:
<ListView
Name="_listView"
Grid.Row="0" Grid.Column="0"
SelectionMode="Single"
IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding SelectedAgent, Mode=TwoWay}"
ItemsSource="{Binding Agents, Mode=OneWay}"
GridViewColumnHeader.Click="ListView_Click"
DependencyProperties:ListBoxClickCommand.ClickCommand="{Binding ShowAgentDetailsCommand}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListViewItem">
<Border
Name="_border"
Padding="2"
CornerRadius="5"
SnapsToDevicePixels="true"
Background="Transparent">
<Controls:AgentStateControl></Controls:AgentStateControl>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="_border" Property="Background" Value="CornflowerBlue" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
The AgentStateControl is my custom control, and it has two rows, the second has a bigger span on the columns. You can create that control however you want.

Resources