I have an application that allows multiple selection of items in the UI with checkboxes. The thing is checkboxes are generated from a file because the company adds or removes selections from the search.
Since I read a file to get all the possible selections available, the checkbox is generated in C# code, not XAML and one requirement for the UI is to have rounded checkboxes. How can I achieve this in C#?
I did this in XAML:
<CheckBox Content="QA Standard" IsEnabled="{Binding CanEdit, UpdateSourceTrigger=PropertyChanged}"
ToolTip="{Binding StatusInfo, UpdateSourceTrigger=PropertyChanged}"
BorderBrush="{Binding StatusColor, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="2"
Margin="5" >
<CheckBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="12" />
</Style>
</CheckBox.Resources>
Tried to redo it in C# but doesn't seems to work:
CheckBox c = new CheckBox() { BorderThickness = new Thickness(2), Content = b, Margin = new Thickness(5) };
var enabled = new Binding() { Source = DataContext, Path = new PropertyPath("CanEdit"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var tooltip = new Binding() { Source = DataContext, Path = new PropertyPath("StatusInfo"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
var border = new Binding() { Source = DataContext, Path = new PropertyPath("StatusColor"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
BindingOperations.SetBinding( c, CheckBox.IsEnabledProperty, enabled );
BindingOperations.SetBinding( c, CheckBox.ToolTipProperty, tooltip );
BindingOperations.SetBinding( c, CheckBox.BorderBrushProperty, border );
var cStyle = new Style( typeof(Border) );
cStyle.Setters.Add( new Setter( Border.CornerRadiusProperty, new CornerRadius( 12.0 ) ) );
c.Resources.Add( "CornerRadiusBorder", cStyle );
Boxes.Children.Add( c );
Just change the key of the resource:
var cStyle = new Style(typeof(Border));
cStyle.Setters.Add(new Setter(Border.CornerRadiusProperty, new CornerRadius(12.0)));
c.Resources.Add(typeof(Border), cStyle);
Related
What's the equivelant of this DataTrigger in C# code?
<DataTrigger
Binding="{Binding}"
Value="{x:Null}">
<Setter
Property=SomeProperty
Value=SomeValue />
</DataTrigger>
I am skeptical on how to create the Binding. Is this correct?
var trigger = new DataTrigger();
trigger.Value = null;
// Is this sufficient?
trigger.Binding = new Binding();
// Code to create the setter
// ...
This would be the equivalent of your XAML:
var trigger = new DataTrigger()
{
Value = null,
Binding = new Binding(".")
};
trigger.Setters.Add(new Setter() { Property = SomeProperty, Value = SomeValue });
I have a wpf datagrid in which I am adding all the columns and style through C#.
I have applied ColumnHeaderStyle as follows:
written setter as :
var fontSizeSetter = new Setter {Property = Control.FontSizeProperty, Value = Convert.ToDouble(font.Size)};
Style as:
var headerStyle = new Style();
headerStyle.Setters.Add(fontSetter);
headerStyle.Setters.Add(fontSizeSetter);
headerStyle.Setters.Add(fontStyleSetter);
headerStyle.Setters.Add(fontWeightSetter);
Applied it to my Datagrid's ColumnHeaderStyle as:
view.DataGrid.ColumnHeaderStyle = headerStyle;
Current problem:
now, when I set FontFamily & FontStyle it gets applied. but column Header textsize remains same. It does not get updated.
Entire Method:
private static void ConfigureFontsForDataGrid(Views.StatusMonitor view, StatusMonitorAgencyFontType font)
{
var fontfamily = new FontFamily(font.Font);
var fontSetter = new Setter { Property = Control.FontFamilyProperty, Value = fontfamily };
var fontSizeSetter = new Setter { Property = Control.FontSizeProperty, Value = Convert.ToDouble(font.Size) };
var fontStyleSetter = new Setter { Property = Control.FontStyleProperty };
var fontWeightSetter = new Setter { Property = Control.FontWeightProperty };
// Defaults
fontWeightSetter.Value = FontWeights.Regular;
fontStyleSetter.Value = FontStyles.Normal;
switch (font.Style)
{
case "Regular":
fontWeightSetter.Value = FontWeights.Regular;
fontStyleSetter.Value = FontStyles.Normal;
break;
case "Bold Italic":
fontWeightSetter.Value = FontWeights.Bold;
fontStyleSetter.Value = FontStyles.Italic;
break;
}
//Configuring data grid cell font
view.DataGrid.CellStyle.Setters.Add(fontSetter);
view.DataGrid.CellStyle.Setters.Add(fontSizeSetter);
view.DataGrid.CellStyle.Setters.Add(fontStyleSetter);
view.DataGrid.CellStyle.Setters.Add(fontWeightSetter);
//Configuring data grid column header font
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontSizeSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontStyleSetter);
view.DataGrid.ColumnHeaderStyle.Setters.Add(fontWeightSetter);
}
Use this code to resize font of Column Header in Datagrid:
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="FontSize" Value="10"/>
</Style>
Can you try below code.
var headerStyle = new Style();
Setter fontSetter = new Setter { Property = Control.FontFamilyProperty, Value = new FontFamily("Calibri") };
headerStyle.Setters.Add(fontSetter);
Setter fontSizeSetter = new Setter { Property = Control.FontSizeProperty, Value = Convert.ToDouble(20) };
headerStyle.Setters.Add(fontSizeSetter);
Setter fontStyleSetter = new Setter { Property = Control.FontStyleProperty, Value = FontStyles.Italic };
headerStyle.Setters.Add(fontStyleSetter);
Setter fontWeightSetter = new Setter { Property = Control.FontWeightProperty, Value = FontWeights.Bold };
headerStyle.Setters.Add(fontWeightSetter);
myGrid.ColumnHeaderStyle = headerStyle;
I wrote following data template in my datagrid resources. It works.
<DataTemplate DataType="{x:Type System:String}">
<TextBlock Text="{Binding}">
<TextBlock.Resources>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontFamily" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontFamily}" />
<Setter Property="FontSize" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontSize}" />
<Setter Property="FontStyle" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontStyle}"/>
<Setter Property="FontWeight" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGridColumnHeader}, Path=FontWeight}"/>
</Style>
</TextBlock.Resources>
</TextBlock>
</DataTemplate>
In code i add columns to listview successfuly. But i want add binding to column than add to listview.
fist is working code in xaml.
<GridViewColumn x:Name="colName" Header="Name" Width="130">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Values, Converter={StaticResource LoadProfileConverter},ConverterParameter=active_total}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
Code behind:
GridViewColumn column = new GridViewColumn();
column.Header = "Header";
column.Width = 130;
FrameworkElementFactory controlFactory = new FrameworkElementFactory(typeof(TextBlock));
var itemsBinding = new System.Windows.Data.Binding("Values")
{
Converter = new LoadProfileConverter(),
ConverterParameter = "active_total",
};
controlFactory.SetBinding(TextBox.TextProperty, itemsBinding);
DataTemplate template = new DataTemplate();
template.VisualTree = controlFactory;
column.CellTemplate = template;
LoadProfileGrid.Columns.Add(column);
var itemsbinding = new Binding("Values")
{
Converter = new LoadProfileConverter(),
ConverterParameter = key
};
controllerFactory.SetBinding(TextBox.TextProperty, itemsbinding);
Create a proper binding using the code above.
Loads of extra properties on the binding object that can assist you.
GridViewColumn column = new GridViewColumn();
column.Header = key;
column.Width = 130;
FrameworkElementFactory controlFactory = new FrameworkElementFactory(typeof(TextBlock));
var itemsBinding = new System.Windows.Data.Binding("Values")
{
Converter = new LoadProfileConverter(),
ConverterParameter = key
};
column.DisplayMemberBinding = itemsBinding;
LoadProfileGrid.Columns.Add(column);
I am trying to get a handle on an element within my DataTemplate in code. I am creating a series of DataGridTemplateColumns in code which I then assign to a grid.
I want to be able to retrieve the DataTemplate from the xaml, find my element and bind to that particular element.
Here is a short sample code what I am trying to achieve:
<DataTemplate x:Key="dataTemplate">
<Grid TextBlock.Foreground="LightGreen" Background="Yellow">
<TextBlock x:Name="txt" />
</Grid>
</DataTemplate>
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Last Name";
Binding b = new Binding("LastName");
DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
TextBlock textBlock = dtemplate.FindName("txt", this);
textBlock.SetBinding(TextBlock.TextProperty, b);
col.CellTemplate = dtemplate;
grid.Columns.Add(col);
Maybe to explain this further:
I am trying to create a set of DataGridTemplateColumns on the fly and apply that to a Datagrid. Since I don't know the property to bind to until the time a source gets presented to me I cannot create a DataTemplate that nested within itself has this binding already build in. Like:
<TextBlock Text={Binding=LastName} ... >
So I am forced to create a set of DataGridTemplateColumn in runtime, look for DataTemplate in my resources and THEN try to bind that column to a property (like LastName) on my datasource.
I would approach this via CellStyle instead:
<DataGrid.Resources>
<Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
<Setter Property="TextBlock.Foreground" Value="LawnGreen"/>
<Setter Property="Background" Value="Yellow"/>
</Style>
</DataGrid.Resources>
DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding("Name");
col.CellStyle = dataGrid.Resources["CellStyle"] as Style;
dataGrid.Columns.Add(col);
There are also ways to do this via DataTemplates but it does not seem necessary in this case (unless your problem is more complex).
My solution to the problem is something like this:
GridView viewLayout = new GridView();
for (int i = 0; i < Apprefs.tables[0].Headers.Count(); i++)
{
GridViewColumn gvc = new GridViewColumn();
string colName = Apprefs.tables[0].Headers[i];
gvc.Header = colName;
gvc.Width = 80;
gvc.CellTemplate = SetTemplete(i); ;
viewLayout.Columns.Add(gvc);
}
listview1.View = viewLayout;
//set binding
listview1.ItemsSource = Apprefs.tables[0].Rows;
and then:
/// <summary>
/// Create DataTemplate
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private DataTemplate SetTemplete(int i)
{
DataTemplate template = new DataTemplate();
//set stack panel
FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
sp.Name = "spBind";
sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
//set textblock
FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
sp.Name = "tbBind";
Binding b = new Binding();
string ito = "[" + i.ToString() + "]"; // bind by index
b.Path = new PropertyPath(ito);
tb.SetBinding(TextBlock.TextProperty, b);
sp.AppendChild(tb);
//set the visual tree of the data template
template.VisualTree = sp;
return template;
}
can someone give the C# equivalent of this xamle code?
<ListBox Width="400" Margin="10"
ItemsSource="{Binding Source={StaticResource myTodoList}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=TaskName}" />
<TextBlock Text="{Binding Path=Description}"/>
<TextBlock Text="{Binding Path=Priority}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
That's because I would like to know how to dynamically add PivotItems into a Pivot, for a windows phone 7 app, with the default Pivot layout generate in VS 2010. For instance, I got this code, but I didn't find a way to add the StackPanel object sp, to ListBox:
// epgXml is an XElement object, wich has channel and programmes tags
// it's an app about a tv guide, where the user clicks on a channel and gets a list of programmes for that channe.
// in th xaml code, I have a grid with a pivot object in it:
<Grid x:Name="LayoutRoot" Background="Transparent">
<controls:Pivot x:Name="MainPivot" ItemsSource="{Binding PivotItems}" Title="ZON EPG">
</controls:Pivot>
</Grid>
// In MainViewModel.cs I have this code:
public void client_GetEPGCompleted(Object sender, GetEPGCompletedEventArgs e)
{
DataTemplate dt = new DataTemplate();
epgXml = e.Result.Output.EPGXml;
if (epgXml != null)
{
//Channels = new List<string>();
// parse the xml and show channels and programmes
var channels = from c in epgXml.Elements("channel")
select c;
foreach (XElement el in channels)
{
PivotItem pi = new PivotItem();
pi.Header = el.Elements("display-name").FirstOrDefault().Value;
ListBox lb = new ListBox();
lb.Margin = new Thickness(0, 0, -12, 0);
//ItemsControl ic = new ItemsControl();
//ic.ItemTemplate = dt;
lb.ItemTemplate = dt;
StackPanel sp = new StackPanel();
sp.Margin = new Thickness(0, 0, 0, 17);
sp.Width = 432;
TextBlock tb = new TextBlock();
Binding binding = new Binding("ProgTitle");
binding.Mode = BindingMode.TwoWay;
tb.SetBinding(TextBlock.TextProperty, binding);
tb.Margin = new Thickness(12, 0, 0, 0);
tb.TextWrapping = TextWrapping.NoWrap;
tb.Style = Application.Current.Resources["PhoneTextExtraLargeStyle"] as Style;
sp.Children.Add(tb);
tb = new TextBlock();
binding = new Binding("ProgStart");
binding.Mode = BindingMode.TwoWay;
tb.SetBinding(TextBlock.TextProperty, binding);
tb.Margin = new Thickness(12, -6, 0, 0);
tb.TextWrapping = TextWrapping.NoWrap;
tb.Style = Application.Current.Resources["PhoneTextSubtleStyle"] as Style;
sp.Children.Add(tb);
tb = new TextBlock();
binding = new Binding("Duration");
binding.Mode = BindingMode.TwoWay;
tb.SetBinding(TextBlock.TextProperty, binding);
tb.Margin = new Thickness(12, 0, 0, 0);
tb.TextWrapping = TextWrapping.NoWrap;
tb.Style = Application.Current.Resources["PhoneTextSubtleStyle"] as Style;
sp.Children.Add(tb);
// get programmes foreach channel
var progrs = from p in epgXml.Elements("programme")
where p.Attributes("channel").FirstOrDefault().Value == el.Attributes("id").FirstOrDefault().Value
select new ItemViewModel()
{
ProgTitle = p.Elements("title").FirstOrDefault().Value,
ProgStart = p.Attributes("start").FirstOrDefault().Value,
Duration = p.Elements("length").FirstOrDefault().Value
};
foreach (ItemViewModel item in progrs)
{
this.Items.Add(item);
}
// create new instance - this holds all the programms for each channel
this.Items = new ObservableCollection<ItemViewModel>();
PivotItems.Add(pi);
}
Thx in advance
You have to use XamlReader to create datatemplates (as in your XAML) on the phone.
See a full example and explanation at http://www.windowsphonegeek.com/tips/wp7-dynamically-generating-datatemplate-in-code
For an example off dynamically adding PivotItems seee How to dynamically add pivot item and add Image to each pivot item?