带有ItemTemplate问题的WPF ListBox

时间:2010-10-26 13:12:25

标签: wpf data-binding .net-3.5 listbox

我有一个列表框,我正在尝试使用它绑定DataTable。我调试代码,DataTable中有数据,但它没有显示DataList中的数据。

<Window.Resources>
    <local:myCurrencyColor x:Key="CurrColor"></local:myCurrencyColor>
</Window.Resources>

<Grid Name="grid1">        
    <ListBox Margin="28,111,130,24" Name="listBox1" >
        <ListBox.ItemTemplate>
            <DataTemplate>                    
                <Label Content="{Binding Path=FullName}" Background="{Binding Path=Salary, Converter={StaticResource CurrColor}}" ></Label>                                            
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

private void Window_Loaded(object sender, RoutedEventArgs e)
{
     // dt.Columns.Add(new DataColumn("FullName", typeof(String)));
     // dt.Columns.Add(new DataColumn("Salary", typeof(Decimal)));

      DataTable dt = GetEmployees();  // it has Salary and Fullname Columns

      grid1.DataContext = dt;
}

  [ValueConversion(typeof(decimal), typeof(Brush))]
  public class myCurrencyColor : IValueConverter
  {
       public object Convert(object value, Type tp, object obj, System.Globalization.CultureInfo cul)
       {
            decimal dml = (decimal)value;
            if(dml < 5)
                return new SolidColorBrush(Colors.Aqua);
            if (dml < 10)
                return new SolidColorBrush(Colors.Azure);
            if (dml < 15)
                return new SolidColorBrush(Colors.BurlyWood);
            if (dml < 20)
                return new SolidColorBrush(Colors.Goldenrod);
            return new SolidColorBrush(Colors.HotPink);
        }
        public object ConvertBack(object value, Type tp, object obj, System.Globalization.CultureInfo cul)
        {
            throw new NotImplementedException();
        }
   }

2 个答案:

答案 0 :(得分:2)

您没有将项目绑定到列表。

尝试添加ItemsSource:

<ListBox ItemsSource="{Binding}" 
         Margin="28,111,130,24" 
         Name="listBox1" >
      .....
</ListBox>

答案 1 :(得分:0)

只需尝试

grid1.ItemsSource=dt.DefaultView;
相关问题