WPF的listbox的用法
阿新 • • 發佈:2019-02-07
1、listbox資料繫結
1)後臺資料繫結
namespace WpfListBoxTest
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.listBox.ItemsSource = GetNumber();
}
private List<int> GetNumber()
{
List<int> listNumber = new List<int>();
for(int i=0;i<99;i++)
{
listNumber.Add(i);
}
return listNumber;
}
}
}
<Grid>
<ListBox Name="listBox"> </ListBox>
</Grid>
2)前臺資料繫結
如果是用的類來儲存資料
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.listBox.ItemsSource=GetNumber();
}
private List<Model> GetNumber()
{
List<Model> listNumber = new List<Model>();
for(int i=0;i<99;i++)
{
listNumber.Add(new Model() { Number=i});
}
return listNumber;
}
}
public class Model
{
public int Number { get; set; }
}
<Grid>
<ListBox Name="listBox" DisplayMemberPath="Number"></ListBox>
</Grid>
一般第二種情況用的更多一些。
2、ListBox加上單選的radiobutton
這裡用上了style這個屬性。
<Window.Resources>
<Style x:Key="radioButtonStyle" TargetType="{x:Type ListBox}">
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<RadioButton Focusable="False" IsChecked="{Binding Path=IsSelected,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}">
<ContentPresenter></ContentPresenter>
</RadioButton>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox Name="listBox" Style="{StaticResource radioButtonStyle}" DisplayMemberPath="Number">
</ListBox>
</Grid>
3、ListBox加上CheckBox,只需要稍微修改一下上面的程式碼即可
<Window.Resources>
<Style x:Key="checkBoxStyle" TargetType="{x:Type ListBox}">
<Setter Property="SelectionMode" Value="Multiple"></Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<CheckBox Focusable="False" IsChecked="{Binding Path=IsSelected,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}">
<ContentPresenter></ContentPresenter>
</CheckBox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox Name="listBox" Style="{StaticResource checkBoxStyle}" DisplayMemberPath="Number">
</ListBox>
</Grid>