Cannot set margin on a custom UserControl in WPF - wpf

I have made a simple UserControl called SmallCtrl. Inside another UserControl called LargeCtrl, I dynamically add SmallCtrl to the list of its children using this code behind (for testing):
public void LargeCtrl_Loaded(object sender, EventArgs args)
{
for (int i = 0; i < 10; i++)
_StackPanel.Children.Add(new SmallCtrl());
}
I use StackPanel with horizontal orientation and I need its child UserControls to have a right margin to create space between them, here is the style resource:
<Grid>
<StackPanel x:Name="_StackPanel" Orientation="Horizontal">
<StackPanel.Resources>
<Style TargetType="{x:Type customCtrls:SmallCtrl}">
<Setter Property="Margin" Value="0,0,10,0"/>
</Style>
</StackPanel.Resources>
</StackPanel>
</Grid>
However, when I load my Window with LargeCtrl the margin doesn't show. If I replace my SmallCtrl with a TextBox, everything works. What is my problem here?

Related

WPF text box animated text characters change

I am trying to make a text-box, where whenever any new character appears/disappears, it is somehow highlighted (eg. the character appears with yellow to black font-color fade in gradient, ...).
In my case, when I write a text in the first text-box, I expect ONLY NEW CHARACTERS in the second text-box to be highlighted, when they appears. Lastly I need to have both texts to be char by char aligned.
Unfortunetaly text-box text property is seen only as one property of the whole string, so when I tried to add animations after TextBox.TextChanged event, but the whole text faded in after every keystroke. My only idea is to write some adapter, which transforms the string in the second text-box to collection of labels, where every label could act as a single character, so the highlighting animations could be performed on the selected individual labels (chars).
This is a minimal sub-issue of my project, which is written using the MVVM pattern. So ideally, I am seeking for solution in xaml, but I am also open to any hacking solution, since characters in the text-box is not designed to be animated.
Here, I include a code to reproduce the window in the example.
MainWindow
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="AnimatedTextBoxStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
<local:AnimatedTextBoxViewModel x:Key="ViewModel"/>
</ResourceDictionary>
</Window.Resources>
<StackPanel DataContext="{StaticResource ViewModel}" Margin="5,5,5,5">
<TextBox Margin="0,0,0,2"
Style="{StaticResource ResourceKey=AnimatedTextBoxStyle}"
Text="{Binding SomeText,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay}">
</TextBox>
<TextBox IsEnabled="False"
Style="{StaticResource ResourceKey=AnimatedTextBoxStyle}"
Text="{Binding SomeText}">
</TextBox>
</StackPanel>
AnimatedTextBoxStyle.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TextBoxCharsAnimation">
<Style x:Key="AnimatedTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="FontFamily" Value="Consolas"/>
<Setter Property="FontSize" Value="16"/>
<Setter Property="Height" Value="26"/>
<Style.Triggers>
<EventTrigger RoutedEvent="TextBox.TextChanged">
<!-- Maybe begin storyboard here? -->
</EventTrigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
AnimatedTextBoxViewModel.cs
using TextBoxCharsAnimation.Support;
namespace TextBoxCharsAnimation
{
class AnimatedTextBoxViewModel : ViewModelBase
{
private string _someText = "";
public string SomeText
{
get => _someText;
set
{
_someText = value;
OnPropertyChanged();
}
}
}
}
We cannot use TextBox control to change some specific character color. We need to use RichTextBox instead of second text box. RichTextBox as the name suggests is rich for customization. You need to hook up the PreviewTextInput event to get the typed char.
Below is the sample code which might need some modifications to suit your requirements.
private void inputRichTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextPointer start;
start = inputRichTextBox.CaretPosition;
TextPointer end = inputRichTextBox.Document.ContentEnd;
TextRange range = new TextRange(start, end);
range.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Green);
}
For colour gradient requirement instead of Brushes.Green you need to replace it with similar to below code.
LinearGradientBrush myHorizontalGradient = new LinearGradientBrush();
myHorizontalGradient.StartPoint = new Point(0);
myHorizontalGradient.EndPoint = new Point(1);
myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Yellow, 0));
myHorizontalGradient.GradientStops.Add(new GradientStop(Colors.Black, 1));

How to get the ActualWidth and ActualHeight dynamically of a customcontrol?

I have a custom control, ccTextBlock placed inside a ScrollViewer. The customcontrol will be changing sizes (vertically) when different strings are sent to it through the binding. The custom control will remain on the display, but will change as text elsewhere on the screen is selected.
How can I obtain the actual width and height of the custom control only after and with each text string sent to it? (Using OnApplyTemplate() did not work as it seems to be called only once on the first construction of the custom control.)
Thanks for any replies.
<ScrollViewer VerticalScrollBarVisibility="Auto">
<Grid>
<wc:ccTextBlock Text="{Binding Text, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" />
</Grid>
</ScrollViewer>
Update: Perhaps a better way to phrase this question would be "How to get the height of an element when it is inside a ScrollViewer". Here is the definition of ccTextBlock:
public class ccTextBlock : Control
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(ccTextBlock), new UIPropertyMetadata(null));
/// <summary>
/// Constructor
/// </summary>
static ccTextBlock()
{
// Initialize as lookless control
DefaultStyleKeyProperty.OverrideMetadata(typeof(ccTextBlock), new FrameworkPropertyMetadata(typeof(ccTextBlock)));
}
public override void OnApplyTemplate()
{
//Effectively apply the template
base.OnApplyTemplate();
Console.WriteLine(String.Format(" ActualHeight is {0}", this.ActualHeight.ToString()));
var x = this.FontSize;
}
}
Where Generic.xaml is:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary">
<Style TargetType="{x:Type local:ccTextBlock}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ccTextBlock}">
<!-- Control Layout -->
<TextBlock Text="{TemplateBinding Text}" TextWrapping="Wrap" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
ActualWidth and ActualHeight are the properties that contain the current width and height of the control.
If you are looking for an Event that notifies about changes, it would be the FrameworkElement.SizeChanged event. You could register for this event in the OnApplyTemplate implementation.

Expander.IsExpanded Binding breaking after first click

am probably doing something but can't figure out my problem. Any help would be really appreciated:
I am having a CustomControl called Section. A Section is collapsible and therefore its ControlTemplate contains an Expander. The Expanders IsExpanded-Property is bound to the Section's IsExpanded Property via TemplateBinding.
When setting IsExpanded on a Section the Expander collapses, but using the toggleButton within the Expander appears to break that binding. Probably by setting a local value to the Expander's IsExpanded-Property. Anyways, after changing the Expander state via Mouse the binding breaks and setting the Section's IsExpanded doesn't do anything.
This however does not happen when putting an Expander into a view and binding its IsExpanded-Property to some DP in the View.
Also notworthy: Snoop does not show any Bindings on the Expander's IsExpanded-Property. It only shows the Value-Source is ParentTemplate. As soon as I click the ToggleButton to Change IsExpanded the Value-Source changes to Local (possibly breaking the former Binding?)
Section.cs:
public class Section : Control
{
static Section()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(Section), new FrameworkPropertyMetadata(typeof(Section)));
}
public static readonly DependencyProperty IsExpandedProperty = DependencyProperty.Register(
"IsExpanded", typeof (bool), typeof (Section), new PropertyMetadata(default(bool)));
public bool IsExpanded
{
get { return (bool) GetValue(IsExpandedProperty); }
set { SetValue(IsExpandedProperty, value); }
}
}
Generic.xaml Style:
<Style TargetType="{x:Type local:Section}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Section}">
<Expander Header="Test" IsExpanded="{TemplateBinding IsExpanded}" >
<Rectangle Fill="Aqua" Height="200" Width="200" />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Any ideas?
So I found the answer which is pretty basic knowledge actually:
TemplateBindings are always ONEWAY no matter what the MetaData states...
Using:
IsExpanded="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=IsExpanded}"
fixed my problem...

Attached behavior binding to element in controltemplate

I am adding an attached behaviour to a slider which will cause it to scroll some content when the thumb is dragged and held over a specific region. (Can't use a straightforward IsMouseOver trigger as the Slider Thumb has MouseCapture.)
The behaviour has 3 properties:
#region IsScrollHoverProperty
public static readonly DependencyProperty IsScrollHoverProperty = DependencyProperty.RegisterAttached(
"IsScrollHover",
typeof(Boolean),
typeof(ScrollHoverAreaBehaviour),
new UIPropertyMetadata(false));
#endregion
#region ScrollLeftRectProperty
public static readonly DependencyProperty ScrollLeftRectProperty = DependencyProperty.RegisterAttached(
"ScrollLeftRect",
typeof(Rectangle),
typeof(ScrollHoverAreaBehaviour),
new UIPropertyMetadata(null));
#endregion
#region ScrollRightRectProperty
public static readonly DependencyProperty ScrollRightRectProperty = DependencyProperty.RegisterAttached(
"ScrollRightRect",
typeof(Rectangle),
typeof(ScrollHoverAreaBehaviour),
new UIPropertyMetadata(null));
#endregion
The IsScrollHoverProperty is being set to true when the user drags the slider, this is all done in the Slider's ControlTemplates.Triggers, and works correctly.
When it's set to true the callback is going to hook PreviewMouseEnterHandlers into the two Rectangles to detect when the mouse enters them.
The Rectangles in question are also defined in the Slider's controltemplate thusly:
<StackPanel Grid.Row="0" Grid.RowSpan="3" HorizontalAlignment="Left" Orientation="Horizontal">
<Rectangle Width="40" Fill="#AAAAAAAA" Name="ScrollLeftRect"/>
</StackPanel>
<StackPanel Grid.Row="0" Grid.RowSpan="3" HorizontalAlignment="Right" Orientation="Horizontal">
<Rectangle Width="40" Fill="#AAAAAAAA" Name="ScrollRightRect"/>
</StackPanel>
The problem I have is binding these Rectangles to the attached ScrollRightRect and ScrollLeftRect Properties. I have tried a few things and suspect I have made a stupid binding error or am trying to do something not allowed. I am currently binding them in the controltemplate.triggers as follows:
<Trigger Property="local:ScrollHoverAreaBehaviour.IsScrollHover" Value="False">
<Setter Property="local:ScrollHoverAreaBehaviour.ScrollLeftRect" Value="{Binding ElementName=ScrollLeftRect}"/>
<Setter Property="local:ScrollHoverAreaBehaviour.ScrollRightRect" Value="{Binding ElementName=ScrollRightRect}"/>
<Setter TargetName="ScrollLeftRect" Property="Fill" Value="Red"/>
<Setter TargetName="ScrollRightRect" Property="Fill" Value="Red"/>
</Trigger>
I know this Trigger is being tripped as the rectangles fill Red as expected.
Can anyone spot what I'm doing wrong from these snippets?
Thanks in advance.
Rob
First, let's confirm you're not doing anything wrong, and the problem has nothing to do with the attached behaviors.
<Button>
<Button.Template>
<ControlTemplate TargetType="Button">
<Border Background="Yellow">
<StackPanel>
<TextBlock x:Name="theText" Text="Hello" />
<ContentPresenter />
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Content" Value="{Binding ElementName=theText, Path=Text}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
</Button>
This snippet should cause "Hello" to appear twice when I mouse over the button, but it doesn't, and I get the same error as you:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=theText'. BindingExpression:Path=Text; DataItem=null; target element is 'Button' (Name=''); target property is 'Content' (type 'Object')
This is explainable - once the binding is set on the Button, it won't be able to find a control named 'theText', because the Button lives in a different NameScope.
An alternative
Some WPF controls need to do something similar to you - they assume that a specific control exists in the tree that they will interact with. But they don't use properties - they use names.
Start by giving the controls a name - the convention is to use "PART_" prefix:
<Rectangle ... Name="PART_ScrollLeftRect" />
Now put code like this in your callback when IsScrollHover is set:
private static void IsScrollHoverSetCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var target = (Slider) d;
if ((bool)e.NewValue == false)
return;
target.ApplyTemplate();
var leftRectangle = target.Template.FindName("PART_ScrollLeftRect", target);
var rightRectangle = target.Template.FindName("PART_ScrollRightRect", target);
// Do things with the rectangles
}
Note that depending on when the IsScrollHost property is set, the template might not be ready yet. In that case, you might want to subscribe to the Loaded or similar event, and then call ApplyTemplate().
Although it might seem more complicated, it has one nice benefit: the markup will be simpler. A designer using Blend won't have to remember to wire up those complicated triggers, they just have to name the controls correctly.
The use of the PART_ prefix is a WPF convention, and normally used along with the TemplatePart attribute. An example of this is the TextBox. When you override the template of a TextBox, it won't function until you add a control named PART_ContentHost.
Update: I just blogged about template parts here: http://www.paulstovell.com/wpf-part-names

WPF - Redrawing a Context Menu when Items change?

I have a ItemsControl in a ScrollViewer, and when the items exceed the width of the ScrollViewer they are put into a ContextMenu and shown as a DropDown instead. My problem is that when the Context Menu is first loaded, it saves the saves the size of the Menu and does not redraw when more commands get added/removed.
For example, a panel has 3 commands. 1 is visible and 2 are in the Menu. Viewing the menu shows the 2 commands and draws the control, but then if you resize the panel so 2 are visible and only 1 command is in the menu, it doesn't redraw the menu to eliminate that second menu item. Or even worse, if you shrink the panel so that no commands are shown and all 3 are in the Menu, it will only show the top 2.
Here's my code:
<Button Click="DropDownMenu_Click"
ContextMenuOpening="DropDownMenu_ContextMenuOpening">
<Button.ContextMenu>
<ContextMenu ItemsSource="{Binding Path=MenuCommands}" Placement="Bottom">
<ContextMenu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Path=Command}" />
<Setter Property="Visibility" Value="{Binding Path=IsVisible, Converter={StaticResource ReverseBooleanToVisibilityConverter}}"/>
</Style>
</ContextMenu.Resources>
<ContextMenu.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=DisplayName}" />
</DataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
</Button.ContextMenu>
</Button>
Code Behind:
void DropDownMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
Button b = sender as Button;
b.ContextMenu.IsOpen = false;
e.Handled = true;
}
private void DropDownMenu_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
ContextMenu cMenu = b.ContextMenu;
if (cMenu != null)
{
cMenu.PlacementTarget = b;
cMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;
cMenu.IsOpen = true;
}
}
I have tried using InvalidateVisual and passing an empty delegate on Render to try and force a redraw, however neither works. I'm using .Net 4.0.
Is MenuCommands a collection? If it is, is it an ObservableCollection?
If you bind a collection to an ItemsControl, that collection must implement INotifyCollectionChanged interface to let the ItemsControl know that the number of items in the collection has changed, so that the control can "redraw" itself.

Resources