VarunJi
VarunJi

Reputation: 694

How to add CheckBox dynamically in WPF C# application

I have "gameListView" ListView in which i want to add Checkbox dynamically. So How can I do this? I am able to add string but not able to add Checkbox. My Code is below.

GridView gridView = new GridView();
gameListView.View = gridView;
//Setting CheckBox here
CheckBox chk = new CheckBox();
chk.IsChecked = varibleName == "1" ? true : false;

gridView.Columns.Add(new GridViewColumn { Header = "Favourite", DisplayMemberBinding = new Binding("Favourite") });
gameListView.Items.Add(new Games.GameItems { GameName = game[0].ToString(), GameDependency = game[1].ToString(), Favourite = chk });

and my Games.GameItems class ia as follow

class GameItems
{
    public string GameName { get; set; }
    public string GameDependency { get; set; }
    public System.Windows.Controls.CheckBox Favourite { get; set; }
}

But my Output shows CheckBox as String :( like below CheckBox

But I want real CheckBox, not the string. So please help me, how can I do this?

Upvotes: 2

Views: 6411

Answers (3)

Suvethan Nantha
Suvethan Nantha

Reputation: 2454

First you need to create a model class for binding each columns of data grid.

public class Test
    {
        public bool Active  { get; set; }

        public Test()
        {
            Active = false;
        }
    }

Then add the following code to your data grid xaml view.

<DataGrid x:Name="gridTest" AutoGenerateColumns="False" Grid.Column="0" HorizontalAlignment="Stretch" Height="254" Margin="15,95,14,0" Grid.Row="0" Grid.RowSpan="1" VerticalAlignment="Top" Width="Auto" Grid.ColumnSpan="1" ItemsSource="{Binding}" KeyUp="gridTest_KeyUp">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Active">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox x:Name="chkActive" IsChecked="{Binding Active, Mode=TwoWay}" IsEnabled="{Binding IsEditable,Mode=TwoWay}" Margin="16,4,0,0" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Then add the following code to the key up event of the data grid.

private void gridTest_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                AddNewRow();
            }
        }

Then, add the following code to initialize the observable collection instance as a global instance.

ObservableCollection<Model.Test> test = new ObservableCollection<Model.Test>(); 

Now, add the following code to implement the AddNewRow method right below the grid key up event implementation.

private void AddNewRow()
        {
            test.Add(new Model.Test());
            gridTest.ItemsSource = test;
        }

Finally run the application and see now you can add checkboxes dynamically to the data grid.

Note: call AddNewRow method after initializecomponent as well.

Upvotes: 0

123 456 789 0
123 456 789 0

Reputation: 10865

What you can do is create a ViewModel for your ListView and set the datacontext to the viewmodel then create a Collection for GameItems.

public class ListViewModel : INotifyPropertyChanged
{
  // Raise OnPropertyChanged on the setter for game items.. also create backing property
  public ObservableCollection<GameItem> GameItems { get; set; }
}

You can do the binding like this in XAML

<ListView ItemsSource="{Binding GameItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <CheckBox IsChecked="{Binding IsChecked}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
</ListView>

What would happen is that it will automatically create CheckBox for each item in the collection and you don't have to worry about anything else but concenctrate on the business logic. WPF is not procedural code unlike WinForms. That's the reason why XAML is created.

Upvotes: 3

SnowballTwo
SnowballTwo

Reputation: 539

You need to define a Datatemplate for the GameItems class, e.g. like the following:

<DataTemplate DataType="{x:Type mynamespace:GameItems}">
    <ContentPresenter Content="{Binding Path=Favourite}"/>
</DataTemplate>

but thats actually not the idea of mvvm. Instead, you can put a boolean property into your gameitems class, also with the name 'Favourite'. Dont forget to make use of INotifyPropertyChanged. The template for this class might look like this:

<DataTemplate DataType="{x:Type mynamespace:GameItems}">
    <CheckBox IsChecked="{Binding Path=Favourite}"/>
</DataTemplate>

Note: dont instanciate controls in your model or viewmodel, if you can avoid it.

Upvotes: 1

Related Questions