2

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?

1
  • There is no need to use CheckBox control as property. Add checkbox by normal way xaml/c# and then bind its value to true or false. Commented Apr 10, 2014 at 12:35

3 Answers 3

3

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.

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

3 Comments

All you are saying is about xaml. But Can't I make this by Code? Like I have added string dynamically. And I need to show or hide Combobox column according to conditions.
@VarunJi But Can't I make this by Code? - NO. XAML is the correct way to do UIs in WPF. WPF is not winforms.
@VarunJi You can do that with XAML x1000 easier than procedural code that you are trying to do. If you want to show/hide combobox columns based on conditions you can use DataTriggers for that.
1

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.

2 Comments

Sorry I am new in WPF C#. So didn't get your answer properly like "mvvm". Also CheckBox is dynamic. I can add or remove that checkbox column anytime.
You can add as many columns as you want, but the content of each column is an instance of the class 'GameItems'. You must tell xaml how to display this class. Thats what a DataTemplate does.
0

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.

Comments

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.