[英]Databinding for Instances of class objects
To preface this I am new to WPF, XAML and C#作为序言,我是 WPF、XAML 和 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.最近两天我一直在寻找一种创建自定义 class object 的方法,该方法将公开一些属性。 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).
然后我想将 UI 中的一些文本框绑定到这些属性,但我希望能够为 class 的多个实例(在我的情况下为模拟)执行此操作。 I am sure this is something simple but I am not understanding how to approach this.
我确信这很简单,但我不明白如何解决这个问题。
Example of the class: 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.编辑:我已经弄清楚如何绑定到 class 但我不确定如何创建另一个 class 实例以单独绑定。
<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?编辑 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 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.