0

I'm creating Radio Buttons dynamically that means I'm looping throught my database items and I'm displaying styled radio buttons and here's my code:

public ObservableCollection<Product> products = new ObservableCollection<Product>(ProductsController.SelectAllProducts());

if (products.Count > 0)
{
    foreach(var item in products)
    {
        SolidColorBrush mySolidColorBrush = new SolidColorBrush();
        mySolidColorBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#004a80"));
        RadioButton a = new RadioButton();
        a.BorderThickness = new Thickness(1);
        a.Background = Brushes.Green;
        a.Foreground = new SolidColorBrush(Colors.Black);
        a.BorderBrush = mySolidColorBrush;
        a.Width = 118;
        a.Height = 70;
        a.Margin = new Thickness(5,0,0,5);
        Style style = Application.Current.Resources["MyRadioButtonAsButtonStyle"] as Style;
        a.Style = style;
        a.ApplyTemplate();
        a.Content = item.OrdinalNumber;
        Image imgControl = (Image)a.Template.FindName("img", a);
        Image imgControlWhite = (Image)a.Template.FindName("whiteImg", a);
        TextBlock text = (TextBlock)a.Template.FindName("text", a);

        if (fileNames.Count > 0)
        {
            if (!fileNames.Any(item.Description.Contains))
            {
                item.IsProcessed = true; // SETTING PROPERTY
            }
        }


        a.Click += (object sender, RoutedEventArgs e) =>
        {
            var radioButton = sender as RadioButton;
            MessageBox.Show(radioButton.Content.ToString());
        };
        text.Text = item.Title;
        imgControl.Source = image;
        spProducts.Children.Add(a);
    }
}

I'm setting IsProcessed which I would like to use when I'm setting background of this radio button which is styled as button.

So for example if IsProcessed = true I would like to set Background to Green, otherwise I would like to set it to Red.

Here is my class:

enter code herepublic class Product : INotifyPropertyChanged { #region Attributes private string _ordinalNumber; private string _title; private string _description; private bool _isProcessed; #endregion

#region Properties
public string OrdinalNumber
{
    get { return _ordinalNumber; }
    set { _ordinalNumber = value; NotifyPropertyChanged("OrdinalNumber"); }
}
public string Title
{
    get { return _title; }
    set { _title = value; NotifyPropertyChanged("Title"); }
}
public string Description
{
    get { return _description; }
    set { _description = value; NotifyPropertyChanged("Description"); }
}

public bool IsProcessed
{
    get { return _isProcessed; }
    set
    {
        _isProcessed = value; NotifyPropertyChanged("IsProcessed");
    }
}

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

}

And here is my custom style where I've set background for first time (To Green):

  <Style x:Key="MyRadioButtonAsButtonStyle" TargetType="RadioButton">
            <Setter Property="FontSize" Value="15" />
            <Setter Property="GroupName" Value="Option" />
            <Setter Property="BorderThickness" Value="1.5" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <!-- and so on for each property...-->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type RadioButton}">
                        <Border Height="{Binding ActualHeight, ElementName=parentStackPanel}" Width="{Binding ActualWidth, ElementName=parentStackPanel}" BorderBrush="#004a80" BorderThickness="{TemplateBinding BorderThickness}">
                            <Grid x:Name="gridProduct" Background="Green">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="80*"></RowDefinition>
                                    <RowDefinition Height="20*"></RowDefinition>
                                </Grid.RowDefinitions>
                                <Image x:Name="slika" Margin="10" Grid.Row="0" Width="Auto" Visibility="Visible"/>
                                <TextBlock x:Name="tekst" Foreground="White" Margin="0,0,0,3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="12"></TextBlock>
                            </Grid>
                        </Border>

                        <ControlTemplate.Triggers>
                            <Trigger Property="IsChecked" Value="True">
                                <Setter TargetName="gridProduct" Property="Background" Value="Orange"/>
                                <Setter TargetName="tekst" Property="Foreground" Value="White"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

So basically I don't know how to check value of item.IsProcessed in app.xaml so I might somehow add setter for background depending on that prop value?

Any kind of help would be great!

Thanks!

6
  • You could implement IValueConverter, which would convert bool to background object. Commented May 7, 2020 at 10:22
  • And you should consider using an ItemsControl instead of creating UI elements in code behind. Commented May 7, 2020 at 10:25
  • @MichałTurczyn How could I do that? Could you help me and provide an example, I'm struggling with this since yesterday :( Commented May 7, 2020 at 10:41
  • @Clemens Since my elements depending on how many items I have in database I thought creating it like this might be good, could you provide your example please? Thanks Commented May 7, 2020 at 10:42
  • 1
    For the "Background based on an item property", this would usually be done by a DataTrigger with a Binding to the item property. Commented May 7, 2020 at 10:47

1 Answer 1

1

How about adding a DataTriggerto your Style?:

<ControlTemplate.Triggers>
    <Trigger Property="IsChecked" Value="True">
        <Setter TargetName="gridProduct" Property="Background" Value="Orange"/>
        <Setter TargetName="tekst" Property="Foreground" Value="White"/>
    </Trigger>
    <DataTrigger Binding="{Binding IsProcessed}" Value="True">
        <Setter TargetName="gridProduct" Property="Background" Value="Green"/>
    </DataTrigger>
</ControlTemplate.Triggers>

For the binding to work, you should set the DataContext of the RadioButton:

foreach (var item in products)
{
    ...
    a.DataContext = item;
    spProducts.Children.Add(a);
}

In general, you would use an ItemsControl that binds to the ObservableCollection<Product> and define the RadioButton in the ItemTemplate.

Sign up to request clarification or add additional context in comments.

1 Comment

who's the boss? mm8 is the boss ! Thanks sir a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.