WPF中的动态页面?如何根据所选值进行控制/

时间:2011-08-19 01:33:40

标签: .net wpf

我是WPF的新手。我正在尝试创建一个在运行时创建的页面,该页面取决于组合框选择。组合框选择有2,3,4,5,所选数字将动态地在下一页上创建一组文本框。

我是否应该使用带有绑定和触发器的内容模板或控件模板或数据模板,还是有另一种方法来创建依赖于用户选择的动态文本框?

1 个答案:

答案 0 :(得分:0)

好吧,我认为没有一种方法可以做这样的事情

您可以在下一页上使用一些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);
        }
    }
}

你可以看到我只有一个对象集合,我添加了bools和Strings ......

根据对象的类型选择datatemplate(您可以在此处使用自己的类型而不是基元)

因此,为了在另一个页面/窗口上创建控件,您可以设置View-Models的集合,将其绑定到ItemsControl,并为每个Type创建一个DataTemplate,而不是使用代码隐藏自己创建每个控件...

但这只是一种方法......不一定是方式