I have created a UserControl with some fields. I would like to use it and bind data to these fields. Most of them are static values but the DataValue
property comes from one property of the MainView.
My code:
<UserControl x:Class="TabletMachineAccess.Controls.DataDisplayer"
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:local="clr-namespace:TabletMachineAccess.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="dataDisplayer"
MaxHeight="100"
mc:Ignorable="d">
<Border Height="auto"
Margin="5"
Padding="5,2,5,2"
BorderBrush="Gray"
BorderThickness="2"
CornerRadius="5">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding DataType}" />
<TextBlock Text=":" />
</StackPanel>
<Separator Style="{StaticResource BasicSeparator}" />
<TextBlock Margin="0,0,0,0"
HorizontalAlignment="Center"
FontWeight="Bold"
Text="{Binding Path=DataValue,
ElementName=dataDisplayer}" />
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
<TextBlock FontWeight="ExtraLight" Text="(" />
<TextBlock FontWeight="ExtraLight" Text="{Binding UnitText}" />
<TextBlock FontWeight="ExtraLight" Text=")" />
</StackPanel>
</StackPanel>
</Border>
</UserControl>
DataDisplayer.xaml.cs
public partial class DataDisplayer : UserControl
{
public double DataValue
{
get { return (double)GetValue(DataValueProperty); }
set { SetValue(DataValueProperty, value); }
}
// Using a DependencyProperty as the backing store for DataValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataValueProperty =
DependencyProperty.Register("DataValue", typeof(double), typeof(DataDisplayer), new PropertyMetadata(9.9));
public string DataType
{
get; set;
}
public string UnitText
{
get; set;
}
public DataDisplayer()
{
InitializeComponent();
this.DataContext = this;
}
}
I try to use it like this in MainView.xaml
<controls:DataDisplayer Grid.Row="1"
Grid.Column="0"
DataType="{x:Static res:Strings.PVUpper}"
DataValue="{Binding PVUpper}"
UnitText="{x:Static res:Strings.KgUnit}" />
I have this in my MainViewModel.cs
public double PVUpper { get; set; }
For those properties, which get data from the res:Strings
works fine and display the correct values, but DataValue
property always shows the default value of the DependencyProperty (9.9). The value of PVUpper
changes in every second in the ViewModel so I would like to see this change on the View as well.