To preface this I am new to WPF, XAML and C#
I have been looking for that last two days now for a method to create a custom class object that will expose some properties. I then want to bind some text boxes in the UI to those properties but I want to be able to do this for multiple instances of a class (Analog in my case). I am sure this is something simple but I am not understanding how to approach this.
Example of the class:
class Analog
{
public string LblA0
{ get; set; }
}
EDIT: I have figured out how to bind to a class but I am unsure how I would create another class instance to bind to separately.
<Grid>
<Grid.DataContext>
<local:Analog/>
</Grid.DataContext>
<TextBlock x:Name="labelAnalog0"
Text="{Binding LblA0, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
EDIT 2: ViewModel class?
class ViewModel
{
public Analog Analog0
{ get; set; }
}
Okay thanks to Clemens I think I understand how to solve this. Here are the classes I have made:
class Analog
{
public Analog(string s)
{
lblA = s;
}
private string lblA;
public string LblA
{
get
{
return lblA;
}
set
{
lblA = value;
}
}
}
class ViewModel
{
Analog analog0 = new Analog("test");
Analog analog1 = new Analog("test2");
public Analog Analog0
{
get
{
return analog0;
}
}
public Analog Analog1
{
get
{
return analog1;
}
}
}
XAML
<TextBlock x:Name="labelAnalog0"
Text="{Binding Analog0.LblA, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="0" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock x:Name="labelAnalog1"
Text="{Binding Analog1.LblA, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="0" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
The call to change the datacontext in the mainpage
analogGrid.DataContext = new ViewModel();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.