Binding ColumDefinition Width - c#

I am creating a Windows 8.1 app using https://slideview.codeplex.com in the Windows 10 with help of Visual Studio 2015.
I have added grid to the design with 1 row and two column. In the first page there is big image and no text and in other pages there is icon and text. So I am putting if 4* in first column for first page and 2* in first for second page all works good but I wanted to make it dynamic in ContentPresenter and then I can assign it from C#.
Kindly somebody help me.
I tried in different way like I put below code in SlideApplicationFrame.cs
#region FirstColumnWidth (DependencyProperty)
/// <summary>
/// header Image First Column Width
/// </summary>
public GridLength FirstColumnWidth
{
get { return (GridLength)GetValue(FirstColumnWidthProperty); }
set { SetValue(FirstColumnWidthProperty, value); }
}
public static readonly DependencyProperty FirstColumnWidthProperty =
DependencyProperty.Register("FirstColumnWidth", typeof(GridLength), typeof(SlideApplicationFrame),
new PropertyMetadata(new GridLength(4, GridUnitType.Star)));
#endregion
#region ContentFirstColumnWidth (Attached DependencyProperty)
public static readonly DependencyProperty ContentFirstColumnWidth =
DependencyProperty.RegisterAttached("ContentFirstColumnWidth", typeof(GridLength), typeof(SlideApplicationFrame), new PropertyMetadata(new GridLength(4, GridUnitType.Star)));
public static void SetContentFirstColumnWidth(DependencyObject o, GridLength value)
{
o.SetValue(ContentFirstColumnWidth, value);
}
public static GridLength GetContentFirstColumnWidth(DependencyObject o)
{
return (GridLength)o.GetValue(ContentFirstColumnWidth);
}
#endregion
Then I use it in my ContentPresenter Like this
<ContentPresenter library:SlideApplicationFrame.ContentFirstColumnWidth="{TemplateBinding FirstColumnWidth}" Grid.Column="1"/>
and at the end in style setter
<ColumnDefinition Width="{Binding library:SlideApplicationFrame.ContentFirstColumnWidth}"/>
Whole Style Setter is as below
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="GridHeader">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding library:SlideApplicationFrame.ContentFirstColumnWidth}"/>
<ColumnDefinition Width="5*"/>
</Grid.ColumnDefinitions>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
and setting from MainPage.xaml.cs
SlideApplicationFrame RootFrame = Window.Current.Content as SlideApplicationFrame;
RootFrame.FirstColumnWidth = new GridLength(4, GridUnitType.Star);
Please help me I will be highly appreciated

Well first you have to have in mind that the values of ColumnDefinition Width and RowDefinition Height are not of type Double but of type GridLength
And after that there are two scenarios that I can think of:
Binding to another element's value
Binding to value from the ViewModel or the code behind
Case 1:
If You're binding to some value that is double you will need to also use a Converter to convert this value to GridLength
Case 2:
If You're binding to something in the code you could create the property of type GridLength and bind directly, or if the value is double again use Converter like in the previous use case.
Some References on the type
GridLength Structure
GridUnitType Enumeration
Auto - The size is determined by the size properties of the content object.
Pixel - The value is expressed as a pixel.
Star - The value is expressed as a weighted proportion of available space.
Edit - Just a simple example of working binding
Still didn't manage to find time to recreate your exact situation so I just used GridView (as it has also header) - Content is purple, header consists of two grid columns - green and red, green is bound to dependency property defined in main page
XAML
<Page
...
x:Name="root">
<Page.Resources>
<Style TargetType="GridView" >
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Grid x:Name="GridHeader" Height="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="{Binding ElementName=root, Path=TestGridLength}"/>
</Grid.ColumnDefinitions>
<Grid Background="Red" Grid.Column="0"></Grid>
<Grid Background="Green" Grid.Column="1"></Grid>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<GridView Background="Purple">
</GridView>
</Page>
Code behind
public GridLength TestGridLength
{
get { return (GridLength)GetValue(TestGridLengthProperty); }
set { SetValue(TestGridLengthProperty, value); }
}
public static readonly DependencyProperty TestGridLengthProperty =
DependencyProperty.Register(
"TestGridLength",
typeof(GridLength),
typeof(MainPage),
new PropertyMetadata(null));
public MainPage()
{
this.InitializeComponent();
this.TestGridLength = new GridLength(10, GridUnitType.Star);
}

Related

Easy Drag Drop implementation MVVM

I am new to MVVM and I am currently trying to add the drag/drop feature to my application. The thing is I already developed the interface in the code-behind but I am trying now to re-write the code into MVVM as I am only at the beginning of the project.
Here is the context: the user will be able to add boxes (ToggleButton but it may change) to a grid, a bit like a chessboard. Below is the View Model I am working on:
<Page.Resources>
<Style TargetType="{x:Type local:AirportEditionPage}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Page}">
<!-- The page content-->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding ToolKitWidth, FallbackValue=50}" />
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="{Binding RightPanelWidth, FallbackValue=400}"/>
</Grid.ColumnDefinitions>
<!-- The airport grid where Steps and Links are displayed -->
<ScrollViewer Grid.ColumnSpan="4" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
<Viewbox Height="{Binding AirportGridHeight}" Width="{Binding AirportGridWidth}" RenderOptions.BitmapScalingMode="HighQuality">
<ItemsControl x:Name="ChessBoard" ItemsSource="{Binding Items}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Width="{Binding CardQuantityRow}" Height="{Binding CardQuantityColumn}" Background="{StaticResource AirportGridBackground}"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="1" Height="1">
<ToggleButton Style="{StaticResource StepCardContentStyle}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding Pos.X}"/>
<Setter Property="Canvas.Top" Value="{Binding Pos.Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Viewbox>
</ScrollViewer>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
Items are basically from a class (child of INotifiedPropertyChanged) with a name, an icon and a position (Point).
Now, I am trying to make the user able to drag and drop the box (ToggleButton) within the grid wherever he/she wants. However, I am totally lost with Commands, AttachedProperties etc. I spent all the whole day on tutorials and tried drag/drop solutions but with my poor knowledge, I don't know how to apply all of this into my code.
On my code-behinded version of the code, it was easy. When the button is left-clicked, I say to a variable of the grid "hey, I am being dragged and dropped". While the user is moving, I changed the Item coordinates and when the user released the left button (left button up), the dragdrop_object variable comes null again.
In the frame of the MVVM, I am totally lost. Could you give me some tracks to help me trough ? I intended to give up with MVVM a lot of time, but I know that it is better to keep up even if every little feature takes litteraly hours for me to implement (it should decrease with time...).
Do not hesitate if you need further details to answer to my question.
I found the solution here : Move items in a canvas using MVVM and here : Combining ItemsControl with draggable items - Element.parent always null
To be precise, here is the code I added :
public class DragBehavior
{
public readonly TranslateTransform Transform = new TranslateTransform();
private static DragBehavior _instance = new DragBehavior();
public static DragBehavior Instance
{
get { return _instance; }
set { _instance = value; }
}
public static bool GetDrag(DependencyObject obj)
{
return (bool)obj.GetValue(IsDragProperty);
}
public static void SetDrag(DependencyObject obj, bool value)
{
obj.SetValue(IsDragProperty, value);
}
public static readonly DependencyProperty IsDragProperty =
DependencyProperty.RegisterAttached("Drag",
typeof(bool), typeof(DragBehavior),
new PropertyMetadata(false, OnDragChanged));
private static void OnDragChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// ignoring error checking
var element = (UIElement)sender;
var isDrag = (bool)(e.NewValue);
Instance = new DragBehavior();
((UIElement)sender).RenderTransform = Instance.Transform;
if (isDrag)
{
element.MouseLeftButtonDown += Instance.ElementOnMouseLeftButtonDown;
element.MouseLeftButtonUp += Instance.ElementOnMouseLeftButtonUp;
element.MouseMove += Instance.ElementOnMouseMove;
}
else
{
element.MouseLeftButtonDown -= Instance.ElementOnMouseLeftButtonDown;
element.MouseLeftButtonUp -= Instance.ElementOnMouseLeftButtonUp;
element.MouseMove -= Instance.ElementOnMouseMove;
}
}
private void ElementOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
((UIElement)sender).CaptureMouse();
}
private void ElementOnMouseLeftButtonUp(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
((UIElement)sender).ReleaseMouseCapture();
}
private void ElementOnMouseMove(object sender, MouseEventArgs mouseEventArgs)
{
FrameworkElement element = sender as FrameworkElement;
Canvas parent = element.FindAncestor<Canvas>();
var mousePos = mouseEventArgs.GetPosition(parent);
if (!((UIElement)sender).IsMouseCaptured) return;
if (mousePos.X < parent.Width && mousePos.Y < parent.Height && mousePos.X >= 0 && mousePos.Y >=0)
((sender as FrameworkElement).DataContext as Step).Pos = new System.Drawing.Point(Convert.ToInt32(Math.Floor(mousePos.X)), Convert.ToInt32((Math.Floor(mousePos.Y))));
}
}
And my DataTemplate is now:
<DataTemplate>
<ContentControl Height="1" Width="1" local:DragBehavior.Drag="True" Style="{StaticResource StepCardContentControl}"/>
</DataTemplate>
I added the FindAncestor static class in a dedicated file like this:
public static class FindAncestorHelper
{
public static T FindAncestor<T>(this DependencyObject obj)
where T : DependencyObject
{
DependencyObject tmp = VisualTreeHelper.GetParent(obj);
while (tmp != null && !(tmp is T))
{
tmp = VisualTreeHelper.GetParent(tmp);
}
return tmp as T;
}
}
(My items are now ContentControls).
As the items' positions within the canvas are directly managed with their Pos variable (Canvas.SetLeft and Canvas.SetTop based on Pos (Pos.X and Pos.Y) with Binding), I just update it according to the MousePosition within the Canvas.
Also, as suggested in a commentary, I will see if there is something better than the ScrollViewer and Viewbox I'm using.

UWP Binding in Style Setter not working

I have problem with creating xaml control. I'm writing new project in VS 2015 in universal app. I want create grid. In this grid I want to have a button. In model I specifi the column (Level) and Row.
this is my code:
<ItemsControl Grid.Row="1" ItemsSource="{Binding Path=TechnologyList}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
<ColumnDefinition Width="14*"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="Control">
<Setter Property="Grid.Column" Value="{Binding Level}" />
<Setter Property="Grid.Row" Value="{Binding Row}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I get a error in line <Setter Property="Grid.Column" Value="{Binding Level}" />
The error: Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED) was in edytor not in running code.
What is wrong? In "old" WPF everything was OK but in Universal App for Windows 10 I have a error.
Can anyone help me ?
As noted in the section Migration notes on the Setter.Value property page on MSDN, UWP/Windows Runtime does not support bindings in Style Setters.
Windows Presentation Foundation (WPF) and Microsoft Silverlight
supported the ability to use a Binding expression to supply the Value
for a Setter in a Style. The Windows Runtime doesn't support a Binding
usage for Setter.Value (the Binding won't evaluate and the Setter has
no effect, you won't get errors, but you won't get the desired result
either). When you convert XAML styles from WPF or Silverlight XAML,
replace any Binding expression usages with strings or objects that set
values, or refactor the values as shared {StaticResource} markup
extension values rather than Binding-obtained values.
A workaround could be a helper class with attached properties for the source paths of the bindings. It creates the bindings in code behind in a PropertyChangedCallback of the helper property:
public class BindingHelper
{
public static readonly DependencyProperty GridColumnBindingPathProperty =
DependencyProperty.RegisterAttached(
"GridColumnBindingPath", typeof(string), typeof(BindingHelper),
new PropertyMetadata(null, GridBindingPathPropertyChanged));
public static readonly DependencyProperty GridRowBindingPathProperty =
DependencyProperty.RegisterAttached(
"GridRowBindingPath", typeof(string), typeof(BindingHelper),
new PropertyMetadata(null, GridBindingPathPropertyChanged));
public static string GetGridColumnBindingPath(DependencyObject obj)
{
return (string)obj.GetValue(GridColumnBindingPathProperty);
}
public static void SetGridColumnBindingPath(DependencyObject obj, string value)
{
obj.SetValue(GridColumnBindingPathProperty, value);
}
public static string GetGridRowBindingPath(DependencyObject obj)
{
return (string)obj.GetValue(GridRowBindingPathProperty);
}
public static void SetGridRowBindingPath(DependencyObject obj, string value)
{
obj.SetValue(GridRowBindingPathProperty, value);
}
private static void GridBindingPathPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var propertyPath = e.NewValue as string;
if (propertyPath != null)
{
var gridProperty =
e.Property == GridColumnBindingPathProperty
? Grid.ColumnProperty
: Grid.RowProperty;
BindingOperations.SetBinding(
obj,
gridProperty,
new Binding { Path = new PropertyPath(propertyPath) });
}
}
}
You would use them in XAML like this:
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="local:BindingHelper.GridColumnBindingPath" Value="Level"/>
<Setter Property="local:BindingHelper.GridRowBindingPath" Value="Row"/>
</Style>
</ItemsControl.ItemContainerStyle>
For a simple workaround for absolute positioning (i.e. binding the Canvas.Left and canvas.Top properties), see this answer.
Wanted to add my experience of this BindingHelper idea from #clemens. It's a neat solution but I found that when targetting a ListViewItem the binding wouldn't access the underlying view model. After debugging it, I found that I needed to make sure the binding was relative to the ListViewItem itself and the associated .Content property to enable it to correctly link to the item's view model.
My particular use case was to set the IsTabStop property of the ListViewItem based on a view model value:
private static void BindingPathPropertyChanged(DependencyObject obj,
DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is string propertyPath)
{
var binding = new Binding
{
Path = new PropertyPath($"Content.{propertyPath}"),
Mode = BindingMode.OneWay,
RelativeSource = new RelativeSource
{
Mode = RelativeSourceMode.Self
}
};
BindingOperations.SetBinding(obj, Control.IsTabStopProperty, binding);
}
}
Hope this helps if anyone else has the problem.

How to get a specific layout in databound list control

I want to layout my items in a Windows Phone 8.1 app, not silverlight, in the following order:
I did some research and tried different panels, but I can't find the right ones :[
I could use a grid and achive that design, BUT I want to add items over a binding and then I would have to change the grid somehow :/
xaml Layout
<Page.DataContext>
<uc:Test/>
</Page.DataContext>
<ScrollViewer>
<ItemsControl ItemsSource="{Binding t}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Aqua"
BorderThickness="3"
Width="100" Height="100">
<TextBlock Text="{Binding}"/>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
test.cs
public class Test
{
public ObservableCollection<string> t { get; set; }
public Test()
{
t = new ObservableCollection<string>();
t.Add("a");
t.Add("b");
t.Add("c");
t.Add("d");
t.Add("e");
}
}
Edit:
ALSO, I did write a wrong information in the comment below, sorry.
Every Item has the same width, so count and width, will/would give me the position in column and row.
Implementation of PrepareContainerForItemOverride so far:
public class ExtendedItemsControl : ItemsControl
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var grid = element as ContentPresenter;
var count = 0; // <- Count of Items in the Grid
var width = 0; // <- width of the current Element
//if (count * width / grid.ActualWidth > 1)
// grid.RowDefinitions.Add(new RowDefinition());
Grid.SetRow(grid, 0);
}
}
You can use a Grid along with an ItemsControl to achieve the ItemsSource binding:
First, set the Grid as the ItemsControl's ItemsPanel
Second, subclass the ItemsControl to set the appropriate Grid.Row and Grid.Column properties on its children
For the first part (it looks from the picture like you have 4 columns and 3 rows):
<local:ExtendedItemsControl ItemsSource="{Binding MyItems}">
<local:ExtendedItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</local:ExtendedItemsControl.ItemsPanel>
</local:ExtendedItemsControl>
For the second part, I suggest overriding OnItemsChanged, and setting the Grid attached properties on each item container as needed. You could do this by using the implicit sequence of the items:
public class ExtendedItemsControl : ItemsControl
{
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
var item2 = this.ItemContainerGenerator.ContainerFromItem(e.NewItems[1]);
Grid.SetColumn(item2, 1);
var item3 = this.ItemContainerGenerator.ContainerFromItem(e.NewItems[2]);
Grid.SetColumn(item3, 2);
Grid.SetColumnSpan(item3, 2);
var item4 = this.ItemContainerGenerator.ContainerFromItem(e.NewItems[3]);
Grid.SetRow(item4, 1);
// etc ...
}
}
The above assumes that your source collection doesn't not change once bound -- if it does change, you might consider overriding PrepareContainerForItemOverride instead, and setting its Grid Row/Column properties with reference to a property on the item model ("ItemIndex" or whatever):
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var contentPresenter = (ContentPresenter)element;
var itemModel = (MyItemModel)item;
switch (itemModel.ItemIndex)
{
case 1:
Grid.SetColumn(contentPresenter, 1);
break;
case 2:
Grid.SetColumn(contentPresenter, 2);
Grid.SetColumnSpan(contentPresenter, 2);
break;
// etc
}
}
There isn't a standard control that will give you the layout you want for arbitrary numbers of different sized items without some custom placement code, but you can customize controls depending on what exactly you need.
Mark Rideout created a customized GridView sample for Windows Store 8.0 at How To: Create a Variable Sized Grouped GridView (like the store) and the techniques you'll use for a Windows Phone Runtime app will be essentially the same. In his control he overrode the PrepareContainerForItemOverride function to look at the individual data items to see if they should be small, medium, or large sized, and then set their columns and spans appropriately in a VariableSizedWrapGrid.
If you want the exact positioning you show (rather than lining things up) and want to limit to 7 then you could set the ItemsPanel to a Grid instead of the VariableSizedWrapGrid and set the items into specific rows and columns in the same way.

DependencyProperty binding error, programmatically

What I have is a well-working C# and XAML code, which does exactly what it is supposed to do, well, almost exactly. I am trying to make my custom, working, DependencyProperty for UserControl - and it is made, well-formed and supposedly working. There are two properties: SumOfApproximationsProperty and SumOfPositionsProperty. These getters and setters simply do not get invoked on certain actions - and this is my problem. They are declared in this UserControl class:
public partial class PresentationCell : UserControl
{
public Label SumOfApproximations;
public Label SumOfPositions;
public PresentationCell()
{
InitializeComponent();
DataContext = this;
this.MinHeight = 40;
this.MinWidth = 40;
SumOfApproximations = this.SumOfApproximation;
SumOfPositions = this.SumOfPosition;
}
public static readonly DependencyProperty SumOfApproximationsProperty =
DependencyProperty.Register("AproximationsProperty", typeof(String),
typeof(PresentationCell), new UIPropertyMetadata(null));
public static readonly DependencyProperty SumOfPositionsProperty =
DependencyProperty.Register("PositionsProperty", typeof(String),
typeof(PresentationCell), new UIPropertyMetadata(null));
public String AproximationsProperty
{
get { return (String)GetValue(SumOfApproximationsProperty); }
set { SetValue(SumOfApproximationsProperty, value); }
}
public String PositionsProperty
{
get { return (String)GetValue(SumOfPositionsProperty); }
set { SetValue(SumOfPositionsProperty, value); }
}
}
As You can see, it is composed of two Labels, that have their own text-setting properties. And here's this UserControl XAML:
// USER CONTROL XAML
<UserControl x:Class="PodstawyModelowaniaISymulacjiRozmytej.Controls.PresentationCell"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*">
</ColumnDefinition>
<ColumnDefinition Width="2*">
</ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="1*">
</RowDefinition>
<RowDefinition Height="2*">
</RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Label Name="SumOfApproximation" Content="{Binding Path=AproximationsProperty}">
</Label>
</Grid>
<Grid Grid.Row="1">
</Grid>
</Grid>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="1*">
</RowDefinition>
<RowDefinition Height="2*">
</RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
</Grid>
<Grid Grid.Row="1">
<Label Name="SumOfPosition"></Label>
</Grid>
</Grid>
</Grid>
</UserControl>
This UserControl is going to be used with DataGrid (as it's cells), which is declared below (in XAML):
// MAIN WINDOW DATAGRIG DECLARATION MAINWINDOW.XAML
<Grid Grid.Row="2" Name="DataThree_Grid">
<DataGrid Name="ResultData_DataGrid" HeadersVisibility="Row" Margin="5 5 5 5"></DataGrid>
</Grid>
Here's the code, that prepares and creates a column in this DataGrid, filled with PresentationCell UserControls:
// MAIN WINDOW CREATE COLUMN FOR DATAGRID FUNCTION MAINWINDOW.XAML.CS
private DataGridTemplateColumn CreatePresentationTemplateColumn(Binding positions, Binding aproximations)
{
DataGridTemplateColumn doubleOnlyTextBoxColumn = new DataGridTemplateColumn();
FrameworkElementFactory factory = new FrameworkElementFactory(typeof(PresentationCell));
DataTemplate dataTemplate = new DataTemplate();
factory.SetValue(PresentationCell.SumOfApproximationsProperty, aproximations);
factory.SetValue(PresentationCell.SumOfPositionsProperty, positions);
dataTemplate.VisualTree = factory;
doubleOnlyTextBoxColumn.CellTemplate = dataTemplate;
return doubleOnlyTextBoxColumn;
}
Other code, that can be deemed useful for You to answer this question:
// MAIN WINDOW INITIALIZING BUTTON MAINWINDOW.XAML.CS
private void SubtractionLR_Button_Click(object sender, RoutedEventArgs e)
{
MyData[] table = new MyData[]
{
new MyData
{
Values = new element[2]
{
new element
{
var1 = 7,
var2 = 6
},
new element
{
var1 = 4,
var2 = 1
}
}
},
new MyData
{
Values = new element[2]
{
new element
{
var1 = 67,
var2 = 3
},
new element
{
var1 = 44,
var2 = 1
}
}
}
};
fillPresentationDataGrid(ResultData_DataGrid, table);
}
Now, after all of the code has been described, the problem lingers here. As You can see, I am trying to create Binding object for my column of PresentationCell UserControls. The problem is, that this String in this Binding is rather unknown for me - its specification and so on. As a result, program cannot find data that should be provided to my control (and for its labels) through this binding. The data should come from MyData[] table. Program shows an error about "cannot find Values" etc. and the cells in DataGrid are blank.
// MAIN WINDOW FILLING PRESENTATION GRID FUNCTION MAINWINDOW.XAML.CS
private void fillPresentationDataGrid(DataGrid dataGrid, MyData[] table)
{
dataGrid.AutoGenerateColumns = false;
for (int i = 0; i < table[0].Values.Length; i++)
{
DataGridTemplateColumn col = CreatePresentationTemplateColumn(new Binding("Values[" + i + "].var1"), new Binding("Values[" + i + "].var2"));
dataGrid.Columns.Add(col);
}
dataGrid.ItemsSource = table;
}
EDIT
All I want is to get that MyData[] table content displayed on DataGrid control using my own custom UserControl. When I change that factory.SetValue(PresentationCell.SumOfApproximationsProperty, aproximations); into factory.SetValue(PresentationCell.SumOfApproximationsProperty, "foo");, the DataGrid will display "foo"'s.
EDIT2
Unfortunately, the problem still exists.
In the constructor of PresentationCell you set this.DataContext = this.
By setting DataContext to your control you are breaking the inheritance of this property and thats why setting the bindings in CreatePresentationTemplateColumn wont work.
To fix that you can remove this line and bind the controls by RelativeSource/ElementName or you can set the dataContext to the main grid in PresentationCell instead of the root level

Is it possible to make fonts scaleable?

All my grids could be small and very big depending on window size but text inside is looking really small on big grid sizes.
My current idea (but I don't know how to realize it yet) is to make Binding for all Grid elements to single font and then change the font size by
override void OnRender(DrawingContext dc) {
depending on window size.
The question is: Is this idea sane and is there other methods for it?
If you have not set the font on inner elements explicitly, they inherit the parent font. So you can change the font size on one of the parent elements (for example the Window itself or the Grid). This changes the font size on all inner elements that has not specified the font size explicitly.
However if your font should be of different sizes, the best solution in my opinion is binding the font size of elements to the font size of the parent window, and using a value converter to do a scale on the font size:
Define a value converter like this:
using System;
using System.Windows.Data;
namespace WPFTest
{
public class FontSizeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
double windowFontSize = (double)value;
var scale = System.Convert.ToDouble(parameter);
return windowFontSize * scale;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
And use it in your xaml:
<Window x:Class="WPFTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:test="clr-namespace:WPFTest"
Title="Window1" Height="300" Width="300" FontSize="20" x:Name="window1">
<Window.Resources>
<test:FontSizeConverter x:Key="fontSizeConverter"/>
</Window.Resources>
<Grid>
<StackPanel Grid.Row="0" Grid.Column="0">
<TextBlock
FontSize="{Binding ElementName=window1, Path=FontSize, Converter={StaticResource ResourceKey=fontSizeConverter}, ConverterParameter=1.5}">
Text 1
</TextBlock>
<TextBlock FontSize="{Binding ElementName=window1, Path=FontSize, Converter={StaticResource ResourceKey=fontSizeConverter}, ConverterParameter=0.7}">
Text 2
</TextBlock>
<TextBlock >Text 3</TextBlock>
</StackPanel>
</Grid>
</Window>
ConverterParameter is used as the scale of the element's font related to the window (specified in ElementName property of the binding).
In this example font of the first TextBlock is 150% of the window font and font of the second TextBlock is 70% of the window. The third TextBlock follows the font size of the window.
I like more this solution as suggested by roberther. It is more aesy and clean.
<Viewbox>
<TextBlock Text="Hello World" />
</Viewbox>
I know this is an old post but it was one of the first things to come up when I searched for the topic, so here is my solution:
I've done this in a project recently for work with text boxes and scaling their content font size relative to the screen. For this I set up an integer value and had font size bound to it.
In my case, my screen height starts at 800x650 and I wanted my font to be size 12 by default so I set the integer value (_ScaledFontSize) to WindowHeight/(650/12).
Everytime the screen size changes, a function is called to recalculate the font size and a property change event is called. This function is where you can add constraints for minimum and maximum font sizes using something simple like:
//Set a minimum font size
if(_ScaledFontSize < 12)
_ScaledFontSize = 12;
In order to enforce this scaled sized, every control that you want to scaled font size on must be bound to the ScaledFontSize property.
Final Result:
Text at application launch
Text at about 1920x1080 (Slightly smaller because not fullscreen)
I was struggling to find something like this for a while and in the end this is what I went with. Luckily the code is pretty simple:
MainWindow.xaml.cs:
using System.Windows;
using System.ComponentModel;
namespace FontScaling
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private int _ScaledFontSize;
public int ScaledFontSize
{
get => _ScaledFontSize;
set => _ScaledFontSize = value;
}
public void PropChange(string name)
{
System.ComponentModel.PropertyChangedEventArgs propertyChangedEvt = new System.ComponentModel.PropertyChangedEventArgs(name);
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, propertyChangedEvt);
}
}
public MainWindow()
{
InitializeComponent();
_ScaledFontSize = (int)Application.Current.MainWindow.Height / 54;
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
_ScaledFontSize = (int)Application.Current.MainWindow.ActualHeight / 54;
PropChange("ScaledFontSize");
}
}
}
MainWindow.xaml:
<Window x:Class="FontScaling.MainWindow"
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:local="clr-namespace:FontScaling"
mc:Ignorable="d"
Title="MainWindow" Height="650" Width="800"
SizeChanged="Window_SizeChanged"
Name="_This">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="200*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="15*"/>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="10*"/>
<ColumnDefinition Width="15*"/>
</Grid.ColumnDefinitions>
<TextBlock
VerticalAlignment="Bottom"
Grid.Row="1"
Grid.Column="1"
Text="Non Scaled TextBlock"/>
<TextBox
Grid.Row="2"
Grid.Column="1"
Text="Non Scaled Text"/>
<TextBlock
VerticalAlignment="Bottom"
Grid.Row="1"
Grid.Column="3"
Text="Scaled TextBlock"
FontSize="{Binding ScaledFontSize, ElementName=_This}"/>
<TextBox
Grid.Row="2"
Grid.Column="3"
Text="Scaled TextBox"
FontSize="{Binding ScaledFontSize, ElementName=_This}"/>
</Grid>
</Window>

Categories