【发布时间】:2017-01-30 05:59:16
【问题描述】:
我是 wpf 的新手,我创建了一个列表框,它将创建一个动态列表项,这里我使用了 datetemplate,它包含两个控件,即两个文本块,一个文本块包含绑定一个值形式的组合框(它是字符串数据类型),另一种是,从代码绑定中绑定一个值。
XAML
<ListBox ItemsSource="{Binding obj}" HorizontalContentAlignment="Left" x:Name="lstbxindex" SelectionMode="Extended" Foreground="White" FontSize="20px" Height="201" BorderBrush="#555555" Margin="80,40,0,0" VerticalAlignment="Top" Width="282" Background="#555555" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="5" >
<TextBlock Height="40px" Width="80px" Text="{Binding roundedhourvalue, FontSize="24" Background="#555555" Foreground="White"></TextBlock>
<TextBlock x:Name="items" Text="{Binding}" Margin="35,0,0,0"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C# (Roundedhour.cs)
public class Roundedhour
{
public string hourvalue { get; set; }
public override string ToString()
{
return string.Format("{0}", hourvalue);
}
}
在这个类中为小时值创建一个属性。对于这个类,我在下面提到的代码隐藏文件中创建了一个对象。创建一个对象并为 hourvalue 变量赋值。
C#(代码隐藏)
{
if (dispatcherTimer1.Interval == TimeSpan.FromSeconds(15))
{
//lstbxindex.Items.Add(lstbxindex.SelectedItem.ToString());
string hrvalue = Convert.ToString(hrvalueinitially);
obj = new Roundedhour();
obj.hourvalue = Convert.ToString(hrvalueinitially);
string roundedhourvalue =obj.hourvalue;
this.DataContext = this;
//lblprojectAhr.Content = string.Join(",", hrvalueinitially + "" + "hr");
}
}
在这里,我为 Rounderhour 类创建了一个对象。将值分配给该属性小时值。但我无法将代码绑定中的值绑定到 XAML 页面。
【问题讨论】:
-
您的
DataContext需要有一个包含{ get; } (getter)的public属性才能从您的Binding中获取值。还要注意Roundedhour中的属性称为hourvalue而不是roundedhourvalue。 当遇到绑定问题时,请务必检查 VisualStudio 中的Output-Window。 - 在那里您会看到缺少的内容...