As an exercise, I decided to create a calculator for bikes in WPF. I created two private fields with setters that trigger OnPropertyChanged(), but I have one databound property ratio, which behaves like readonly, because it is dynamically computed. When I run the program, the text fields are displayed, the initial values are displayed correctly, the "working" word is displayed in the handler with the changed property, but the text block is rationot updated.
I suspect that this is due to the way the "getted" property is interesting, it would be absolutely necessary to add a personal field for everyone, I wonder if there should be some DependencyProperty in this ... But actually I have reached my limit of knowledge about this and cannot make this trivial program work.
This is my model:
class SingleGearsetModel : INotifyPropertyChanged
{
public SingleGearsetModel()
{
crank = 44;
cog = 16;
}
private int _crank;
private int _cog;
public int crank {
get{return _crank;}
set{
_crank = value;
OnPropertyChanged("crank");
}
}
public int cog {
get{return _cog;}
set{
_cog = value;
OnPropertyChanged("cog");
}
}
public double ratio
{
get {
return (double)crank / (double)cog;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string arg)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(arg));
Console.Writeline("working");
}
}
}
This is my XAML:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="CalculadorFixaWPF.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<DockPanel x:Name="LayoutRoot">
<TextBox Text="{Binding crank, Mode=TwoWay}"/>
<TextBox Text="{Binding cog, Mode=TwoWay}"/>
<TextBlock Text="{Binding ratio, StringFormat={}{0:0.00}}"/>
</DockPanel>
</Window>
And this is in my code (MainWindow.xaml.cs):
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
this.DataContext = new SingleGearsetModel();
}
}
Thanks for reading!
source
share