arm*_*lmd 1 c# data-binding wpf observablecollection
我正在使用WPF.我ObservableCollection的ToggleButton:
private ObservableCollection<ToggleButton> myg = new ObservableCollection<ToggleButton>();
Run Code Online (Sandbox Code Playgroud)
我想将这些ObservableCollection控件(ToggleButtons)绑定为WrapPanel子项.每次我使用myg.Add(new ToggleButton)我希望它WrapPanel自动添加控件.
示例XAML:
<WrapPanel Name="test1">
<!-- I want to bind (add) these controls here -->
</WrapPanel>
Run Code Online (Sandbox Code Playgroud)
有可能,如果是 - 怎么样?也许还有其他类似的方法吗?
这很容易,但有一点点:
要利用'observable collection'功能,需要绑定它,但没有像ItemsSourceon 这样的属性WrapPanel.
解:
使用ItemsControl并将其面板设置为WrapPanel托管项目.
XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Button Grid.Row="0"
Click="Button_Click"
Content="Add toggle" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
码
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private readonly ObservableCollection<ToggleButton> _collection;
public MainWindow()
{
InitializeComponent();
_collection = new ObservableCollection<ToggleButton>();
DataContext = _collection;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var toggleButton = new ToggleButton
{
Content = "Toggle" + _collection.Count
};
_collection.Add(toggleButton);
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:
分配您的收藏到DataContext你直接处理您的救治WrapPanel中,<ItemsControl Grid.Row="1" ItemsSource="{Binding}">绑定到这个属性默认.
| 归档时间: |
|
| 查看次数: |
1243 次 |
| 最近记录: |