I have style resource in my button to make it rounded, and i want to create it using c#(code behind), how do i do it?
<Button.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="5"/>
</Style>
</Button.Resources>
Create the Style:
Style style = new Style() { TargetType = typeof(Border) };
style.Setters.Add(new Setter() { Property = Border.CornerRadiusProperty, Value = new CornerRadius(5) });
style.Seal();
Add it to the Button:
button.Resources.Add(typeof(Border), style);
XAML:
<Button x:Name="button" Content="..." />
Related
I have a Datagrid on my Window with 2 Columns added in XAML and 1 Column added in the code behind. I managed to remove the blue color from the first 2 columns by adding a DataGridCell Style with the background set to null.
But in the code behind I cannot get it working.
This is the Window.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:System="clr-namespace:System;assembly=mscorlib" x:Class="WpfApp1.MainWindow"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<DataGrid x:Name="CandidatesEpisodesMatrix"
ColumnWidth="*"
AutoGenerateColumns="False" CanUserAddRows="False" HeadersVisibility="Column" SnapsToDevicePixels="True" SelectionUnit="Cell" RowDetailsVisibilityMode="Collapsed" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" />
<DataGridCheckBoxColumn/>
<!-- Other columns are added dynamically -->
</DataGrid.Columns>
<System:Object/>
<System:Object/>
</DataGrid>
</Grid>
</Window>
And this is my code behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
AddMatrixColumn();
}
private void AddMatrixColumn()
{
var factory = new FrameworkElementFactory(typeof(CheckBox));
var columnCellTemplate = new DataTemplate(typeof(CheckBox));
columnCellTemplate.VisualTree = factory;
var style = new Style();
style.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Stretch));
style.Triggers.Add(new DataTrigger
{
Binding = new Binding("IsSelected"),
Value = true,
Setters =
{
new Setter(BackgroundProperty, Brushes.BlueViolet),
new Setter(BorderBrushProperty, Brushes.Aqua),
}
});
var headerStyle = new Style();
headerStyle.Setters.Add(new Setter(HorizontalAlignmentProperty, HorizontalAlignment.Center));
var column = new DataGridTemplateColumn();
column.Header = "episode.Name";
column.HeaderStyle = headerStyle;
column.CellTemplate = columnCellTemplate;
column.CellStyle = style;
CandidatesEpisodesMatrix.Columns.Add(column);
}
}
I had hoped to change the background color by adding a Trigger to the style, but it doesn't work. What am I doing wrong?
Found it! I was almost there with the Trigger. Not a DataTrigger, but a normal Trigger should be used. This is what the trigger should be:
style.Triggers.Add(new Trigger
{
Property = DataGridCell.IsSelectedProperty,
Value = true,
Setters =
{
new Setter(BackgroundProperty, Brushes.Transparent), // Or whatever color
new Setter(BorderBrushProperty, Brushes.Transparent),
}
});
I need to add a DataTrigger dynamically based on user interaction with a search function, so it cannot be done in XAML. However, the basic aim of what I am trying to do can be seen from the XAML code below. It needs to change the visibility of a button based on a ToggleButton's IsChecked state.
XAML:
<ToggleButton Name="myToggleButton" />
<Button Name="myButton">
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=myToggleButton, Path=IsChecked}"
Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=myToggleButton, Path=IsChecked}"
Value="False">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button>
This is what I have in C# to try to produce the same functionality of the above XAML.
C#:
ToggleButton myToggleButton = new ToggleButton();
Button myButton = new Button();
Style style = new Style( typeof( Button ) );
DataTrigger tbChecked = new DataTrigger()
{
Binding = new Binding( "IsChecked" ) { Source = myToggleButton },
Value = true
},
tbNotChecked = new DataTrigger()
{
Binding = new Binding( "IsChecked" ) { Source = myToggleButton },
Value = false
};
tbChecked.Setters.Add( new Setter( Button.VisibilityProperty, Visibility.Visible ) );
tbNotChecked .Setters.Add( new Setter( Button.VisibilityProperty, Visibility.Collapsed ) );
style.Triggers.Add( tbChecked );
style.Triggers.Add( tbNotChecked );
myButton.Style = style;
For the life of me, I have not been able to figure out why it won't work. What am I missing?
maybe, you can try this:
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="b2v"/>
</StackPanel.Resources>
<CheckBox x:Name="switchCheckBox" Content="Show/Hide" VerticalAlignment="Center"/>
<TextBlock Text=" "/>
<Button Content="Test Button" Visibility="{Binding ElementName=switchCheckBox, Path=IsChecked, Converter={StaticResource b2v}}" Padding="25,5"/>
</StackPanel>
How do I apply a style not on the whole textblock, but only on the first run (the Bold)?
I want to apply the style "XXXFontName-Bold" on the Bold Run AND the style "XXXFontName-Thin" on the rest.
// add button
Button btn = new Button();
TextBlock contextText = new TextBlock();
contextText.Inlines.Add(new Bold(new Run(label.Substring(0,1))));
contextText.Inlines.Add(new Style()); <===== OBVIOUS ERROR HERE
contextText.Inlines.Add(label.Substring(1));
contextText.FontSize = 25;
contextText.Style = FindResource("XXXFontName-Thin") as Style;
btn.Content = contextText;
3 Example Styles, Example to set runs in XAML with the styles and new lines and also how to set them in the code behind in your button
Your code behind:
public MainWindow()
{
InitializeComponent();
Button btn = new Button();
TextBlock contextText = new TextBlock();
var newRun = new Run("BoldGreenRunStyle");
newRun.Style = FindResource("BoldGreenRunStyle") as Style;
contextText.Inlines.Add(newRun);
newRun = new Run("ItalicRedRunStyle");
newRun.Style = FindResource("ItalicRedRunStyle") as Style;
contextText.Inlines.Add(newRun);
newRun = new Run("ThinPurpleRunStyle");
newRun.Style = FindResource("ThinPurpleRunStyle") as Style;
contextText.Inlines.Add(newRun);
btn.Content = contextText;
Container.Children.Add(btn);
}
Your XAML
<Window.Resources>
<Style TargetType="Run" x:Key="BoldGreenRunStyle">
<Setter Property="Foreground" Value="Green"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Style>
<Style TargetType="Run" x:Key="ItalicRedRunStyle">
<Setter Property="Foreground" Value="Red"></Setter>
<Setter Property="FontWeight" Value="Normal"></Setter>
<Setter Property="FontStyle" Value="Italic"></Setter>
</Style>
<Style TargetType="Run" x:Key="ThinPurpleRunStyle">
<Setter Property="Foreground" Value="Purple"></Setter>
<Setter Property="FontWeight" Value="Thin"></Setter>
</Style>
</Window.Resources>
<StackPanel x:Name="Container">
<Label Content="From XAML"></Label>
<TextBlock>
<TextBlock.Inlines>
<Run Style="{StaticResource BoldGreenRunStyle}">BoldGreenRunStyle</Run>
<LineBreak/>
<Run Style="{StaticResource ItalicRedRunStyle}">ItalicRedRunStyle</Run>
<LineBreak/>
<Run Style="{StaticResource ThinPurpleRunStyle}">ThinPurpleRunStyle</Run>
<LineBreak/>
</TextBlock.Inlines>
</TextBlock>
</StackPanel>
I try to add button from code and add triggers and setters to it. I wolud like to create button like this:
<Button Height="25" Width="100" Name="TestColorButton" Margin="10, 5, 0, 0">
<TextBlock Text="{Binding Text, ElementName=ColorTextBox}"></TextBlock>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="{Binding Fill, ElementName=NormalRectangle}"/>
<Setter Property="Template"> <!-- I need this setter -->
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{Binding Fill, ElementName=MouseOverRectangle}"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{Binding Fill, ElementName=ClickRectangle}"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
I found how to do everything except one setter. I checked it by comment. I tried many times and I got only something like this:
ContentPresenter contentPresenter = new ContentPresenter
{
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
Border border = new Border();
var binding = new Binding("Background");
binding.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
BindingOperations.SetBinding(border, BackgroundProperty, binding);
border.Child = contentPresenter;
ControlTemplate controlTemplate = new ControlTemplate(typeof (Button));
Setter templateSetter = new Setter(TemplateProperty, controlTemplate);
style.Setters.Add(templateSetter);
I know it can not work, but I don't know how to do it differently.
Template can be added by code easily. here an example with a label.
// create the label with some context
var lbl = new Label() { DataContext = new ImageData(imagePath) };
// control template i want to put on the label
ControlTemplate labelLayout = new ControlTemplate();
// will be my main container that will be by template later on
FrameworkElementFactory grdContainer = new FrameworkElementFactory(typeof(Grid));
grdContainer.Name = "myContainer";
// another element but ill put it in the grid (template)
FrameworkElementFactory myImage = new FrameworkElementFactory(typeof(Image));
// some bindings and setters
myImage.SetBinding(Image.SourceProperty, new Binding("ImagePath"));
myImage.SetValue(Image.HorizontalAlignmentProperty, HorizontalAlignment.Center);
myImage.SetValue(Image.HeightProperty, height);
myImage.SetValue(Image.WidthProperty, double.NaN);
myImage.SetValue(Image.SnapsToDevicePixelsProperty, true);
// add the image to the grid
grdContainer.AppendChild(myImage);
// set the visual layout of the template to be the grid (main container)
labelLayout.VisualTree = grdContainer;
// set the template (line you are looking for mostly)
lbl.Template = labelLayout;
Let's say, I've got something like this (in MainPage.xaml):
<Page.Resources>
<Style TargetType="TextBlock" x:Key="TextBlockStyle">
<Setter Property="FontFamily" Value="Segoe UI Light" />
<Setter Property="Background" Value="Navy" />
</Style>
</Page.Resources>
Then, I would like to apply that StaticResource style to my dynamic created TextBlock (file MainPage.xaml.cs).
Is there any possibility to do this instead of doing something like this:
myTextBlock.FontFamily = new FontFamily("Segoe UI Light");
myTextBlock.Background = new SolidColorBrush(Color.FromArgb(255,0,0,128));
It has been more than 4 years now since this question was asked, but I want to post an answer just to share my findings.
For example if there is a Style BlueButton described in Application resource in App.xaml (Xamarin Cross-Platform App development), it can be used as follows
<?xml version="1.0" encoding="utf-8" ?><Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SharedUi.App">
<Application.Resources>
<ResourceDictionary>
<Style x:Key="BlueButton" TargetType="Button">
<Setter Property="TextColor" Value="White" />
<Setter Property="FontSize" Value="20" />
<Setter Property="BackgroundColor" Value="Blue"/>
<Setter Property="HeightRequest" Value="70"/>
<Setter Property="FontAttributes" Value="Bold"/>
</Style>
</ResourceDictionary>
</Application.Resources></Application>
Then in the code behind
Button newButton1 = new Button
{
Text = "Hello",
WidthRequest = (double)15.0,
Style = (Style)Application.Current.Resources["BlueButton"]
};
You can set, Something like this,
TextBlock myTextBlock= new TextBlock ()
{
FontFamily = new FontFamily("Segoe UI Light");
Style = Resources["TextBlockStyle"] as Style,
};
You can use this:
Style textBlockStyle;
try
{
textBlockStyle = FindResource("TextBlockStyle") as Style;
}
catch(Exception ex)
{
// exception handling
}
if(textBlockStyle != null)
{
myTextBlock.Style = textBlockStyle;
}
or TryFindResource approach:
myTextBlock.Style = (Style)TryFindResource("TextBlockStyle");