最近 使用WPF 框架编程。设计ComboBox 控件使用。
使用。net.4.5.2 的版本
一下介绍几种 绑定数据的方法:
1 推荐,最简洁,自由:
前台:
<Grid Name="bindGrid" DataContext="{Binding}">
<ComboBox SelectedIndex="{Binding SelIdx}" ItemsSource="{Binding SelectStrItems, Mode=OneTime}"/>
</Grid>
后台:
{
public void SetInfo(WinBindInfo wbInfo)
{
this.bindGrid.DataContext = wbInfo;
}
}
public class WinBindInfo
{
public int SelIdx { get; set; } = 0;
public string[] SelectStrItems { get; set; } = null;
}
方法2 :微软推荐的,也许有其他优点:
<Grid >
<Grid.Resources>
<ObjectDataProvider x:Key="students"
ObjectType="{x:Type albert: DevSatusInfo }"
MethodName="GetStudentList"/>
</Grid.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource students}}"/>
</Grid>
后台:
public class DevSatusInfo
{
public List<String> GetSensorList()
{
#region 示范代码
List<String> allSensorStrList= new List<String>();
for (int j = 0; j < 5; j++)
{
allSensorStrList.Add(j.ToString("00"));
}
#endregion
return allSensorStrList;
}
}
3 其他:
添加控件名后 后台手动添加:
foreach (var item in Agreement.CurrencyAgreement.SampleList)
{
this.samplingList.Items.Add(item.timeStr);
}
前台添加固定项:
<ComboBox>
<ComboBoxItem Content="Red"/>
<ComboBoxItem Content="Blue"/>
<ComboBoxItem Content="Black"/>
</ComboBox>