我是WPF的新手。我正在嘗試創建一個在運行時創建的依賴於組合框選擇的頁面。組合框的選擇有2,3,4,5,選擇的數字將動態地在下一頁上創建一組文本框。WPF中的動態頁面?你如何根據選定的值進行控制/
我是否應該使用內容模板或控件模板或數據模板以及綁定和觸發器,還是有另一種方法來創建依賴於用戶選擇的動態文本框?
我是WPF的新手。我正在嘗試創建一個在運行時創建的依賴於組合框選擇的頁面。組合框的選擇有2,3,4,5,選擇的數字將動態地在下一頁上創建一組文本框。WPF中的動態頁面?你如何根據選定的值進行控制/
我是否應該使用內容模板或控件模板或數據模板以及綁定和觸發器,還是有另一種方法來創建依賴於用戶選擇的動態文本框?
嗯,我認爲沒有做這樣的事情
你可以使用一些ItemsControl
下一個頁面上,併爲它提供(至少一個)DataTemplate
,設置了一個TextBox
或別的東西的一種方式你喜歡下頁...
這裏是將一些控件添加到ListBox
每當你點擊一個Button
XAML的例子:
背後<Window x:Class="DynamicPage.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<CollectionViewSource x:Key="VS"/>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Vertical">
<Button Content="Add a String" Click="StringButton_Click"/>
<Button Content="Add a Bool" Click="BoolButton_Click"/>
</StackPanel>
<ListBox Grid.Column="2" ItemsSource="{Binding Source={StaticResource VS}}">
<ListBox.Resources>
<DataTemplate DataType="{x:Type sys:String}">
<StackPanel Orientation="Horizontal">
<TextBlock>I am a String Value</TextBlock>
<TextBox Text="{Binding Path=.}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type sys:Boolean}">
<StackPanel Orientation="Horizontal">
<TextBlock>I am an Bool Value</TextBlock>
<CheckBox IsChecked="{Binding Path=.}"/>
</StackPanel>
</DataTemplate>
</ListBox.Resources>
</ListBox>
</Grid>
</Window>
代碼:
using System.Windows;
using System.Windows.Data;
using System.Collections.ObjectModel;
namespace DynamicPage
{
public partial class MainWindow : Window
{
public ObservableCollection<object> MyList = new ObservableCollection<object>();
public MainWindow()
{
InitializeComponent();
((CollectionViewSource)this.Resources["VS"]).Source = MyList;
}
private void StringButton_Click(object sender, RoutedEventArgs e)
{
MyList.Add("Some Text");
}
private void BoolButton_Click(object sender, RoutedEventArgs e)
{
MyList.Add(false);
}
}
}
,你可以看到我只有對象的集合,我添加的bool和字符串...
的DataTemplate中被選中的基礎上的類型對象(你可以在這裏使用你自己的類型代替基元)
所以爲了在另一個頁面/窗口上創建控件,你可以設置一個View-Models的集合,將它綁定到ItemsControl,併爲每個Type設置一個DataTemplate而不是肌酸克每一個控制在你自己的代碼後面...
但這只是一種方法做到這一點...不一定這樣的方式