我正在尝试将我的对象列表绑定到列表框。
这是对象列表定义:
class LoadFactory : INotifyCollectionChanged
{
public ObservableCollection<Load> Loads = new ObservableCollection<Load>();
public LoadFactory()
{
AddLoad(new Load(15));
AddLoad(new Load(12));
AddLoad(new Load(25));
}
public int LoadCount()
{
return Loads.Count();
}
public void AddLoad(Load load)
{
Loads.Add(load);
if (CollectionChanged != null)
CollectionChanged(this, new NotifyCollectionChangedEventArgs(new NotifyCollectionChangedAction()));
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public ObservableCollection<Load> GetLoads()
{
return new ObservableCollection<Load>(Loads);
}
}
public class Load
{
public static int LoadCount=0;
public int Index = 0;
public Load(float LoadMagnitude)
{
magnitude = LoadMagnitude;
Index = LoadCount;
LoadCount++;
}
private float magnitude;
public float Magnitude
{
get
{
return magnitude;
}
set
{
magnitude = value;
}
}
public float ToFloat()
{
return magnitude;
}
public override string ToString()
{
return magnitude.ToString() + " ft";
}
}
这是我的 XAML:
<Window x:Class="Sunny3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Sunny3"
Title="MainWindow" Height="500" Width="1000">
<Grid>
<Grid Name="motherGrid">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Button Grid.Row="1" Click="Button_Click_1">Hello</Button>
<ListBox Grid.Row="2" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<DataTemplate.Resources>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="3"></Setter>
<Setter Property="FontSize" Value="20"></Setter>
<Setter Property="Width" Value="70"></Setter>
<Setter Property="Foreground" Value="Blue"></Setter>
</Style>
</DataTemplate.Resources>
<StackPanel>
<Grid>
<TextBox Text="{Binding Path=.}"></TextBox>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
而我背后的代码:
public partial class MainWindow : Window
{
LoadFactory LF;
public MainWindow()
{
LF = new LoadFactory();
InitializeComponent();
this.DataContext = LF.Loads;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Load newone = new Load(154);
LF.AddLoad(newone);
}
}
问题是我似乎无法将负载绑定到文本框。
有什么建议么?