How to access controls in inside Control Template in a Custom control - c#

I am developing a WPF Custom Control
<ResourceDictionary xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MultiSelectComboBox">
<Style TargetType="{x:Type local:MultiSelectComboBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MultiSelectComboBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions >
<telerik:RadComboBox x:Name="PART_ComboBox"
Grid.Column="0"
ItemsSource="{Binding ItemsSource,RelativeSource={RelativeSource TemplatedParent}}" >
<telerik:RadComboBox.Template>
<ControlTemplate>
<TextBlock x:Name="PART_ComboText"/>
</ControlTemplate>
</telerik:RadComboBox.Template>
<telerik:RadComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="PART_ItemCheckBox"/>
<TextBlock x:Name="PART_ItemText"/>
</StackPanel>
</DataTemplate>
</telerik:RadComboBox.ItemTemplate>
</telerik:RadComboBox>
<CheckBox Grid.Column="1" x:Name="PART_SelectAllCheckBox" VerticalAlignment="Center" IsChecked="{TemplateBinding IsAllSelected}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
I want to get access to PART_ComboText
I can access controls define there using GetTempalteChild method
part_comboBox = GetTemplateChild("PART_ComboBox") as RadComboBox;
But I am unable to access controls inside Control Template. For an example
which is in Control template couldn't access that. I know we couldn't access control templates from code behind.
I tried this method. It also does not work.
part_comboBox = GetTemplateChild("PART_ComboBox") as RadComboBox;
var comboBoxTemplate = part_comboBox.Template;
part_comboText = (TextBlock) comboBoxTemplate.FindName("PART_ComboText", part_comboBox);

This is probably because the RadComboBox isn't fully loaded when your trying to find the TextBlock inside.
Check its IsLoaded property to know if it's ready or not. If it's not, you'll have to defer the execution of your code until its Loaded event is raised.
part_comboBox = GetTemplateChild("PART_ComboBox") as RadComboBox;
if (part_comboBox.IsLoaded)
{
part_comboText = part_comboBox.FindName("PART_ComboText");
DoStuffWithComboText(part_comboText);
}
else
{
part_comboBox.Loaded = new RoutedEventHandler((o, e) =>
{
part_comboText = part_comboBox.FindName("PART_ComboText");
// Or... part_comboText = part_comboBox.Template.FindName("PART_ComboText", part_comboBox); ... can't remember which one was correct in this case
DoStuffWithComboText(part_comboText);
}
}

Use OnApplyTemplate() to manipulate child controls and call this inside the static method PropertyChangedCallback:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
if (Template != null)
{
Image partImage = Template.FindName("PART_Image", this) as Image;
if (partImage != null)
{
if (String.IsNullOrEmpty(Picture))
{
partImage.Visibility = Visibility.Hidden;
partImage.Width = 0;
}
else
{
partImage.Visibility = Visibility.Visible;
partImage.Width = 16;
}
}
}
}
public string Picture
{
get => (string)GetValue(PictureProperty);
set => SetValue(PictureProperty, value);
}
private static void OnPictureChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ButtonUI control = d as ButtonUI;
control.OnApplyTemplate();
}
The generic in themes is simple:
<Style TargetType="{x:Type local:ButtonUI}" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Height" Value="24" />
<Setter Property="Width" Value="100" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ButtonUI}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<WrapPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<Image Name="PART_Image" Source="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:ButtonUI}},Path=Picture}" Height="16" Width="16" Margin="2,0,2,0" />
<TextBlock Name="PART_Caption" Text="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:ButtonUI}},Path=Caption}" Margin="2,0,2,0" />
</WrapPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Related

How to change resource template element's property using only XAML?

The main idea is to have a button with default icon "yes.png" and text in it "Accept", but have a possibilty to change these two properties using only XAML(at the designing process, without compiling).
Current XAML window which has an area at the bottom with only two buttons:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<ResourceDictionary>
<Style x:Key="tb1" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border BorderThickness="1" BorderBrush="#000" Padding="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Image Source="Files/Icons/no.png" Margin="10,0,0,0" Height="16" Width="16"></Image>
<TextBlock Grid.Column="1" Margin="10" VerticalAlignment="Center">Cancel</TextBlock>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Margin" Value="0,10,10,10"></Setter>
</Style>
</ResourceDictionary>
</Window.Resources>
<Grid>
<Border BorderThickness="0, 1, 0, 0" BorderBrush="#e7e7e7" HorizontalAlignment="Stretch" Padding="0,0,0,0" VerticalAlignment="Bottom" Height="61">
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="b_Accept" Style="{StaticResource tb1}"></Button> <!-- How to change an icon to "yes.png" and TextBlock's content to "Accept"? -->
<Button x:Name="b_Cancel" Style="{StaticResource tb1}"></Button>
</StackPanel>
</Border>
</Grid>
</Window>
Result:
Please,
How is it possible to change second button's icon to "no.png"(Source property) and TextBlock's text(Content) to "Cancel"(only using XAML and not User Control)?
What would be the very right way(the easiest?)? For example, in this post we might use DataTemplate, but might be that's not that we want to because DataTemplate changes the whole element, while we need only one property.
Although, I am right that there are only dependency property(C#) available for that purpose which expects compiling?
Thank you
You can create your custom Button class or an Attached Property to extend the Button:
public class IconControl : DependencyObject
{
#region IconUri attached property
public static readonly DependencyProperty IconUriProperty = DependencyProperty.RegisterAttached(
"IconUri", typeof(ImageSource), typeof(IconControl), new PropertyMetadata(default(ImageSource)));
public static void SetIconUri([NotNull] DependencyObject attachingElement, ImageSource value)
{
attachingElement.SetValue(IconControl.IconUriProperty, value);
}
public static ImageSource GetIconUri([NotNull] DependencyObject attachingElement) => (ImageSource) attachingElement.GetValue(IconControl.IconUriProperty);
#endregion
#region Label attached property
public static readonly DependencyProperty LabelProperty = DependencyProperty.RegisterAttached(
"Label", typeof(String), typeof(IconControl), new PropertyMetadata(default(String)));
public static void SetLabel([NotNull] DependencyObject attachingElement, String value)
{
attachingElement.SetValue(IconControl.LabelProperty, value);
}
public static String GetLabel([NotNull] DependencyObject attachingElement) => (String) attachingElement.GetValue(IconControl.LabelProperty);
#endregion
}
Modified Style for the Button:
<Style x:Key="IconButtonStyle"
TargetType="{x:Type Button}">
<!-- Set the default values -->
<Setter Property="IconControl.IconUri" Value="/Files/Icons/no.png"/>
<Setter Property="IconControl.Label" Value="Cancel"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border BorderThickness="1"
BorderBrush="#000"
Padding="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Image Source="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(IconControl.IconUri)}"
Margin="10,0,0,0"
Height="16"
Width="16" />
<TextBlock Grid.Column="1"
Margin="10"
VerticalAlignment="Center"
Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(IconControl.Label)}" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Margin"
Value="0,10,10,10"></Setter>
</Style>
Usage:
<!-- Override the default content -->
<Button Style="{StaticResource IconButtonStyle}"
IconControl.IconUri="/Files/Icons/yes.png"
IconControl.Label="Accept" />

Custom control with TextBox and Button does not inherit styles from parent

I created a user control with a TextBox and a Button, but it does not want to use the parent's style. However, my control appeas to have the parent's style at design time, but at runtime the styles disappear.
There is my TextBoxButton.xaml
<Style x:Key="{x:Type Common:TextBoxExtension}" TargetType="{x:Type Common:TextBoxExtension}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Common:TextBoxExtension}">
<Border x:Name="border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="True">
<DockPanel>
<Button DockPanel.Dock="Right" Padding="-3.0" Margin="2"
Width="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType={x:Type TextBoxBase},Mode=FindAncestor}}"
Content="..."
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Command="{TemplateBinding Command}"/>
<ScrollViewer Name="PART_ContentHost" Focusable="False"
HorizontalScrollBarVisibility="Hidden"
VerticalScrollBarVisibility="Hidden"/>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Also, there is TextBoxExtension.cs
public class TextBoxExtension : TextBox
{
static TextBoxExtension()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextBoxExtension),
new FrameworkPropertyMetadata(typeof(TextBoxExtension)));
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(TextBoxExtension),
new PropertyMetadata(null));
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
}
Usage in window
<Common:TextBoxExtension FontSize="14" Text="{Binding VaultPath, UpdateSourceTrigger=PropertyChanged}" Margin="5" Grid.Column="1" Grid.Row="2" />
<Common:TextBoxExtension FontSize="14" Command="{Binding SetLocalPath}" Text="{Binding LocalPath, UpdateSourceTrigger=PropertyChanged}" Margin="5" Grid.Column="1" Grid.Row="3" />
What i expected to get
What i get when run the program
Want to add that buttons is working

how to select item on ExpanderDoubleClick Header in Listview

I have a ListView with different itemTemplate, and each itemTemplates have an ExpanderDoubleClick : Expander inside
I would like to select items in extended Mode in a listview with custom selection design (declared in each items UserControl).
So here is my xaml for the listView:
<ListView x:Name="ListViewModules" ItemsSource="{Binding ListOfModules}"
ItemContainerStyle="{StaticResource ContainerListViewItemStyle}"
ItemTemplateSelector="{DynamicResource ModuleTemplateSelector}"
SelectionMode="Extended"
dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True"
dd:DragDrop.UseDefaultDragAdorner="True"
Grid.Column="0" Grid.Row="0" Height="494" Width="634" Background="#FFCDCDCD"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Visible"
BorderBrush="#666666" BorderThickness="1" Padding="0"
ClipToBounds="True" SnapsToDevicePixels="True" >
</ListView>
with styles for removing the standard blue selection (declared in App.xaml):
<Style x:Key="ContainerListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Setter Property="Margin" Value="2,2,2,0"/>
<Setter Property="dd:DragDrop.DragSourceIgnore" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border x:Name="Bd" BorderBrush="Transparent" BorderThickness="0" Background="Transparent" Padding="0" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I have different ItemTemplates with each "UserControl's" and here an exemple of one of them with it's selection design :
<UserControl x:Class="Topinambour.Templates.Modules.DelayTemplate" ...>
<Grid Width="602" MinHeight="24">
<Grid.ColumnDefinitions> <ColumnDefinition Width="40"/><ColumnDefinition /> </Grid.ColumnDefinitions>
<ToggleButton x:Name="TgBtIsActive" IsChecked="{Binding IsChecked}" IsThreeState="{Binding IsThreeState}" Grid.Column="0" Height="24" Width="40" click="TgBtIsActive_Click"/>
<templates:ExpanderDoubleClick x:Name="ModuleExpander" IsExpanded="{Binding IsExpanded, Mode=OneWay}" Height="auto" Template="{DynamicResource TemplateExpander}" Grid.Column="1" Margin="4,0,0,0" Collapsed="Expander_Collapsed" Expanded="Expander_Expanded" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
<templates:ExpanderDoubleClick.Resources>
<Style x:Key="ExpanderHeaderStyle" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border x:Name="BorderIndent" BorderBrush="Gray" BorderThickness="1" Height="24" Width="558" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Padding="{Binding Indent}">
... my Header Content ...
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsExpanded}" Value="true">
<Setter Property="IsEnabled" TargetName="TbComment" Value="true"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListViewItem}}" Value="true">
<Setter Property="Background" TargetName="headerCanvas" Value="#999999"/>
<Setter Property="BorderBrush" TargetName="TbComment" Value="#666666"/>
<Setter Property="Foreground" TargetName="LbHeaderTitle" Value="White"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</templates:ExpanderDoubleClick.Resources>
<Border Background="White" BorderBrush="#666666" BorderThickness="1,0,1,1" Height="136" Width="558">
<Grid>
... my Expanded Content ...
</Grid>
</Border>
</templates:ExpanderDoubleClick>
</Grid>
and here the ExpanderDoubleClick.cs :
public class ExpanderDoubleClick: Expander
{
private static readonly DependencyPropertyKey IsMouseDoubleClickedPropertyKey = DependencyProperty.RegisterReadOnly(
"IsMouseDoubleClicked",typeof(Boolean),typeof(ExpanderDoubleClick),new FrameworkPropertyMetadata(false));
public static readonly DependencyProperty IsMouseDoubleClickedProperty = IsMouseDoubleClickedPropertyKey.DependencyProperty;
public Boolean IsMouseDoubleClicked
{
get { return (Boolean)GetValue(IsMouseDoubleClickedProperty); }
}
static ExpanderDoubleClick()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ExpanderDoubleClick), new FrameworkPropertyMetadata(typeof(ExpanderDoubleClick)));
}
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
ContentControl contentControl = base.GetTemplateChild("HeaderSite") as ContentControl;
if (contentControl != null)
{
contentControl.AddHandler(ContentControl.MouseDoubleClickEvent, new MouseButtonEventHandler(ExpanderHeader_MouseDoubleClick), true);
}
}
private void ExpanderHeader_MouseDoubleClick(Object sender, MouseButtonEventArgs e)
{
base.SetValue(IsMouseDoubleClickedPropertyKey, !IsMouseDoubleClicked);
base.IsExpanded= !base.IsExpanded;
}
}
the selection is not working when I click on the header of the expander but if I open it and click inside the expandedContent, it select the item ! what did I miss ? thank you for the reply.
I finally found a pretty good solution that keep my extended mode selection.
since the header seams to not receive Click event to handle.
I looked up the tree debug, and it shows that the click on header does not go through the "ListViewItem"
so I add an OnMouseLeftButtonDown Event on my border x.Name="BorderIdent" and then add RaisedEvent back to it's itemTemplate
like so :
private void BorderIndent_OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ListViewItem lvItem = UITools.FindAncestor<ListViewItem>(e.OriginalSource as DependencyObject);
bool isListViewItem = lvItem != null;
if (isListViewItem)
{
lvItem.RaiseEvent(e);
}
}
UITools.FindAncestor : is here
and all worked perfectly :)

How to save position after reload DataGrid in WPF

I'm talking about DataGrid not DataGridView!
What I'm doing here is refreshing datagrid which contains <DataGrid.GroupStyle> and I'm showing my data from database grouped by number of order, and what I want to do is refresh my datagrid.
Here is my code:
public MainWindow()
{
try
{
InitializeComponent();
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.WindowState = WindowState.Maximized;
var ordersList = OrdersController.localOrders();
collectionViewSource.Source = ordersList;
collectionViewSource.GroupDescriptions.Add(new PropertyGroupDescription("NumberOfOrder"));
DataContext = collectionViewSource;
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(8);
timer.Tick += timer_Tick;
timer.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void timer_Tick(object sender, EventArgs e)
{
var ordersList = OrdersController.localOrders();
collectionViewSource.Source = null;
collectionViewSource.Source = ordersList;
DataContext = collectionViewSource;
datagrid1.ScrollIntoView(datagrid1.Items[datagrid1.Items.Count - 1]);
}
}
XAML:
<DataGrid HorizontalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Hidden" BorderBrush="#83D744" IsSynchronizedWithCurrentItem="False" VerticalGridLinesBrush="Transparent" Grid.Column="0" RowHeaderWidth="0" CanUserAddRows="False" AutoGenerateColumns="False" x:Name="datagrid1" Margin="10,150,8,50" Background="Transparent" RowBackground="#FF494949" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" ItemsSource="{Binding}">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="#83D744"/>
<Setter Property="Opacity" Value="1"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="FontSize" Value="18"/>
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="Height" Value="50"/>
</Style>
<Style x:Key="TextInCellCenter" TargetType="{x:Type TextBlock}" >
<Setter Property="TextAlignment" Value="Center"/>
</Style>
<Style TargetType="{x:Type TextBlock}" x:Key="RightAligElementStyle">
<Setter Property="TextAlignment" Value="Right"/>
</Style>
<Style TargetType="{x:Type TextBlock}" x:Key="LeftAligElementStyle">
<Setter Property="TextAlignment" Value="Left"/>
</Style>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</DataGrid.Resources>
<DataGrid.Columns >
<DataGridTextColumn Binding="{Binding ProductName}" ElementStyle="{StaticResource LeftAligElementStyle}" Header="NAZIV ARTIKLA" MinWidth="350" Foreground="White" FontSize="20" FontFamily="Verdana" />
<DataGridTextColumn Binding="{Binding Quantity}" ElementStyle="{StaticResource TextInCellCenter}" Header="KOLIČINA" MinWidth="200" Foreground="White" FontSize="20" FontFamily="Verdana" />
</DataGrid.Columns>
<DataGrid.GroupStyle>
<!-- Style for groups at top level. -->
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" Background="Black" Opacity="0.7">
<Expander.Header >
<DockPanel Height="50" Margin="0,0,0,0" Name="dockPanel" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=ActualWidth}">
<Button Name="btnFinishOrder" Content="Finish Order" Margin="0,0,55,5" DockPanel.Dock="Right" Click="btnFinishOrder_Click" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left" VerticalAlignment="Bottom" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="#83D744" Background="Transparent" BorderBrush="#83D744" Width="130" Height="40">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush= "{TemplateBinding BorderBrush}"
Background= "{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
<Button Name="btnTakeIt" Click="btnTakeIt_Click" Content="Take it" Margin="0,0,20,5" DockPanel.Dock="Right" FontSize="12" BorderThickness="1.5" HorizontalAlignment="Left" VerticalAlignment="Bottom" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" Foreground="#83D744" Background="Transparent" BorderBrush="#83D744" Width="130" Height="40">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
<TextBlock FontWeight="Normal" FontFamily="Verdana" FontSize="20" Height="25" Foreground="#83D744" Text="{Binding Path=Name,StringFormat= Number of Order:# {0}}" />
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
after reload data, cell selection jumps on first column and scrollbars is reset. How to save position of DataGrid?
If you need to scroll to specific item, just save the index and use:
dataGrid.ScrollIntoView(dataGrid.Items[itemIndex]);
You can use this to scroll to the last item in the DataGrid:
dataGrid.ScrollIntoView(dataGrid.Items[dataGrid.Items.Count - 1]);
EDIT:
There seems to be a problem with DataGrid scrolling when using CollectionViewSource and grouping.
I managed to get it to work the other way... Instead of
dataGrid.ScrollIntoView(dataGrid.Items[dataGrid.Items.Count - 1])
try using the following code to do the scrolling:
if (datagrid1.Items.Count > 0)
{
var border = VisualTreeHelper.GetChild(datagrid1, 0) as Decorator;
if (border != null)
{
var scrollViewer = border.Child as ScrollViewer;
if (scrollViewer != null) scrollViewer.ScrollToEnd();
}
}

How to Specify CornerRadius for custom TextBox control in WPF?

I have created custom ctextbox with the following code. But I am not able provide the roundcorner border for this.
public class FilteredTextBox : TextBox
{
public FilteredTextBox()
: base()
{
IsNumeric = false;
IsRegex = false;
IsRequired = false;
ErrorMsg = "";
RegexText = "";
HorizontalAlignment = HorizontalAlignment.Stretch;
Margin = new Thickness(0);
BorderThickness = new Thickness(1);
var border = new Border {CornerRadius = new CornerRadius(4)};
}
}
Please guide me on this?
You can do this with a style for your custom TextBox:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Grid.Resources>
<Style x:Key="CustomTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border
CornerRadius="4"
Padding="2"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1" >
<ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Grid.Resources>
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<CustomTextBox Style="{StaticResource CustomTextBoxStyle}" Text="TextBox with CornerRadius" BorderBrush="Black" />
</Grid>
</Grid>
</Page>
hope this helps
I wanted to add this as a tack-on to punker76's great response:
If you ever want to modify any of the default styles for the current FrameworkElement objects available in .Net there are a number of ways to approach it, but I always like this handy tool:
Show Me The Template

Categories