简体   繁体   中英

Dynamically Create TextBlock and TextBox in XAML WPF

My Question Is I have a grid where number of TextBlock and TextBox will vary as per the ComboBox SelectedItem Change

So, what I want is that I have written a function for get the details of the TextBlock and TextBox .

C# Function

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);
    }
}

Now In the XAML I was trying:

<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>

But I don't know how to create a TextBlock or TextBox with ItemSource binding.

You can change the ItemTemplate of your ItemsControl .

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

In above snippet replace PropertyName with DeviceAttributes member you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM