0

The task is a DataGrid with an unknown number of columns and rows. One column contains textbox, checkbox, imagebutton "Image-ComboBox" and "Text-Combobox" (both non-editable). According to a database query, the grid should be created dynamically. In a DataTemplate, the elements are to be arranged horizontally and those that are not required are to be hidden using "Collapsed". The "Source Binding" works, but unfortunately not the "SelectedValue".

<Window x:Class="Artikelprüfwerte.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Artikelprüfwerte"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<Window.DataContext>
    <local:VM/>
</Window.DataContext>

<Window.Resources>
    <Style TargetType="TextBox">
        <Setter Property="Visibility" Value="Collapsed"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Feldart}" Value="Textbox">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
            <Trigger Property="Tag" Value="rt">
                <Setter Property="Background" Value="OrangeRed"/>
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="CheckBox">
        <Setter Property="Visibility" Value="Collapsed"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Feldart}" Value="Checkbox">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="ComboBox">
        <Setter Property="Visibility" Value="Collapsed"/>
        <Style.Triggers>
            <DataTrigger Binding="{Binding Feldart}" Value="Combobox">
                <Setter Property="Visibility" Value="Visible" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<Grid>
    <DataGrid Name="dgrArtikel" ItemsSource="{Binding ocDessin}" IsReadOnly="True" SelectionMode="Single" HorizontalAlignment="Left" FrozenColumnCount="1" Width="Auto" Margin="20,0,0,0"
              ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" 
              AutoGenerateColumns="False" AlternationCount="2">
    </DataGrid>
</Grid>
namespace Artikelprüfwerte
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        for (int i = 1; i <= 3; i++)
        {
            prcAddSpalte(i, (i == 2 ? true : false));
        }
    }

    private void prcAddSpalte(int prmSpalte, bool prmProduktionsende)
    {
        DataGridTemplateColumn Spalte = new DataGridTemplateColumn();
        Spalte.Header = "Spalte-" + prmSpalte;

        FrameworkElementFactory tbxFactory = new FrameworkElementFactory(typeof(TextBox));
        Binding Bindung = new Binding("Textbox" + prmSpalte);
        tbxFactory.SetValue(TextBox.TextProperty, Bindung);
        if (prmProduktionsende)
            tbxFactory.SetValue(TagProperty, "rt");

        FrameworkElementFactory chkFactory = new FrameworkElementFactory(typeof(CheckBox));

        FrameworkElementFactory imgFactory = new FrameworkElementFactory(typeof(Image));
        imgFactory.SetBinding(Image.SourceProperty, new Binding());
        imgFactory.SetValue(Image.HeightProperty, (double)40.0);
        imgFactory.SetValue(Image.WidthProperty, (double)40.0);
        DataTemplate cellTemplate1 = new DataTemplate();
        cellTemplate1.DataType = typeof(Image);
        cellTemplate1.VisualTree = imgFactory;
        FrameworkElementFactory cbxFactory1 = new FrameworkElementFactory(typeof(ComboBox));
        cbxFactory1.SetValue(ComboBox.ItemsSourceProperty, new Binding("lstCombobox3"));
        cbxFactory1.SetValue(ComboBox.ItemTemplateProperty, cellTemplate1);

        //no Binding-Error, but no Data?!
        Binding selectedItemBinding = new Binding() { Path = new PropertyPath("SelectedItem1"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
        cbxFactory1.SetBinding(ComboBox.SelectedValueProperty, selectedItemBinding);
        cbxFactory.SetValue(ComboBox.ItemTemplateProperty, (DataTemplate)this.Resources["cbxImagetemplate"]);

        FrameworkElementFactory splFactory = new FrameworkElementFactory(typeof(StackPanel));
        splFactory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
        if (prmProduktionsende)
            splFactory.SetValue(StackPanel.BackgroundProperty, Brushes.Red); //Styletrigger via Tag out of function?!
        splFactory.AppendChild(tbxFactory);
        splFactory.AppendChild(chkFactory);
        splFactory.AppendChild(cbxFactory1);

        DataTemplate cellTemplate = new DataTemplate();
        cellTemplate.VisualTree = splFactory;
        Spalte.CellTemplate = cellTemplate;

        dgrArtikel.Columns.Add(Spalte);
    }
}
 }

ViewModel

namespace Artikelprüfwerte
{
class VM : Property
{
    private ObservableCollection<DSZeile> _ocDessin = new ObservableCollection<DSZeile>(); public ObservableCollection<DSZeile> ocDessin { get => _ocDessin; set { _ocDessin = value; OnPropertyChanged("ocDessin"); } }

    public VM()
    {
        prcSpalte(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

    }

    private void prcSpalte(string prmProgrammpfad)
    {
        ocDessin.Add(
            new DSZeile
            {
                Feldart = "Textbox",
                Color = "sw",
                Textbox1 = "abc",
                Textbox2 = "def",
                ocCombobox1 = new ObservableCollection<string>{ @"Bilder\Akustik.png", @"Bilder\Akustik.png" }
            });

        ocDessin.Add(
            new DSZeile
            {
                Feldart = "Checkbox",
                Color = "rt",
                Textbox1 = "hij",
                Textbox2 = "klm",
                ocCombobox1 = new ObservableCollection<string> { @"Bilder\Akustik.png", "5", "6" }
            });

        ocDessin.Add(
            new DSZeile
            {
                Feldart = "Combobox",
                Color = "rt",
                Textbox1 = "hij",
                Textbox2 = "klm",
                lstCombobox3 = new List<string> { prmProgrammpfad + "/Akustik.png", prmProgrammpfad + "/Akustik.png", prmProgrammpfad + "/Fleckschutz.png" }
            });
    }
}

}

Structure of row:

public class DSZeile : Property
{
    public string Feldart { get; set; }
    public string Color { get; set; }

    public string Textbox1 { get; set; }
    public bool Checkbox1 { get; set; }
    public ObservableCollection<string> ocCombobox1 { get; set; }

    public string Textbox2 { get; set; }
    public bool Checkbox2 { get; set; }
    public ObservableCollection<string> ocCombobox2 { get; set; }

    public string Textbox3 { get; set; }
    public bool Checkbox3 { get; set; }
    public List<string> lstCombobox3 { get; set; }
    public string SelectedItem1 { get; set; }
}
Orace
  • 7,822
  • 30
  • 45
Snip
  • 1
  • TL;DR; LOL. Also : build your binding in C# instead of XAML. R U Mad bro ? Finally, `SelectedValue` can't work if you don't set the `SelectedValuePath` property. See this answer [Difference between SelectedItem, SelectedValue and SelectedValuePath](https://stackoverflow.com/questions/4902039/difference-between-selecteditem-selectedvalue-and-selectedvaluepath) Pro Tip: don't use `SelectedValue` use `SelectedItem` it's more reliable. – Orace May 17 '22 at 13:40
  • 1
    Try setting the `DataContext` of the ComboBox to relevant `Binding` property in the Object . eg`cbxFactory1.SetBinding(....`. It may not be bount to the correct object. – rufw91 May 17 '22 at 13:41

1 Answers1

0

You should bind to the SelectedItem, not the SelectedValue:

cbxFactory1.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding);

Also read my comment (use XAML instead of C#) and this question.

Orace
  • 7,822
  • 30
  • 45