【问题标题】:Dynamically Create TextBlock and TextBox in XAML WPF在 XAML WPF 中动态创建 TextBlock 和 TextBox
【发布时间】:2015-01-01 17:55:12
【问题描述】:

我的问题是我有一个网格,其中 TextBlockTextBox 的数量将根据 ComboBox SelectedItem 变化而变化

所以,我想要的是我编写了一个函数来获取TextBlockTextBox 的详细信息。

C#函数

public void GetAdditionalAttributes()
{
    using (Entities _entities = new Entities())
    {
        var attributeAll = (from c in _entities.AdditionalAttributeValues
                            where c.DeviceID == 35
                            select new AttributesClass { AttributeValue = c.AdditionalAttributeValue1, AttributeName = c.AdditionalAttribute.Name }).ToList();
        DeviceAttributes = new ObservableCollection<AttributesClass>(attributeAll);
    }
}

现在在我尝试的 XAML 中:

<Style x:Key="AdditionalAttributeDisplay"
        TargetType="Grid"
        x:Name="AdditionalAttributeDisplay"
        >
    <Style.Resources>
        <Style TargetType="ItemsControl">
                <Setter Property="ItemsSource"
                    Value="{Binding DeviceAttributes}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding SelectedValue, ElementName=DeviceTypeComboBox}"
                                Value="1">
                    <Setter Property="ItemsSource"
                            Value="{Binding DeviceAttributes}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Style.Resources>
</Style>

但我不知道如何使用ItemSource 绑定创建TextBlockTextBox

【问题讨论】:

    标签: c# wpf visual-studio xaml


    【解决方案1】:

    您可以更改ItemsControlItemTemplate

      <Style TargetType="ItemsControl">
         <Setter Property="ItemTemplate">
             <Setter.Value>
                 <ItemContainerTemplate>
                     <Grid>
                         <TextBox Width="100" Height="20" Text={Binding AttributeName}/>
                     </Grid>
                 </ItemContainerTemplate>
             </Setter.Value>
         </Setter>
      </Style>
    

    在上面的 sn-p 中,将 PropertyName 替换为您想要的 DeviceAttributes 成员

    【讨论】:

    • 但是如何将名称或值绑定到 TextBox 和 TextBlock 那里?
    • Text="{Binding PropertyName}"
    • 您必须将 PropertyName 替换为您的 DataContext 属性
    • 在我的 GRID 中 &lt;Grid Style="{StaticResource AdditionalAttributeDisplay}"&gt; &lt;/Grid&gt; 对吗?
    • 使用 snoop control 并 snoop ItemsControl 来查找 DataContext。您将在 snoop 中获得 DataContext 的属性。将其绑定到文本框。它与网格样式无关
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2013-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多