selected checkbox in WPF - wpf

I have a lot of check boxes in my WPF form. I want to get the selected checkbox value alone. In Winforms we can use foreach(checkbox ck in controls), but I cannot use like that in WPF Forms. How can i get the selected checkbox in WPF?

First of all, WPF is not just another replacement for WinForms, So the tricks in Winforms might be little different than WPF. WPF is all about DataBinding, so read about MVVM pattern which will really help you in WPF development.
Now coming to the way to go with MVVM approach fort this, Imagine your ViewModel class contains a collection of bool. Now the DataTemplate has CheckBox.IsChecked property bind to the boolean, So when you change the checkbox the collection will hold the changed booleans appropriately.
public List<bool> MyBoolCollection{get; set;}
<ItemsControl ItemsSource="{Binding MyBoolCollection}" ...>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>

Can you data bind the IsChecked property for each CheckBox? Bind it to a member variable of the container class. At least this way you can iterate over the member variables to determine if any are checked.

Related

WPF - SuggestAppend for Textbox

I am looking for a textbox control that suggests words as the user types, similar to SuggestAppend for textboxes in winforms, except for WPF. I have looked around on the WPFToolkit and haven't really found anything that fits my needs.
Thanks.
Declare an enum AutoCompleteMode too with value(Append, None,SuggestAppend,Suggest)
public enum AutoCompleteMode
Create an custom UserControl with TextBox and ItemControls. Handle the KeyDown event of TextBox. Popup an custom List to show the suggestion list(ItemControls in here). Then Handle the selection of the ItemControls. Can custom the style of hte ItemControls's ItemTemplate. Apply the AutoCOmpleteMode in this UserControl and handle the Enum changed in the code behind.
WpfToolkit contains AutoCompleteBox that you can use for auto suggest feature.
You will have to define a collection for items to suggest (SuggestionItems) and set it as ItemsSource on AutoCompleteBox control.
<someNamespaceAlias:AutoCompleteBox
ItemsSource="{Binding SuggestionItems}"
SelectedItem="{Binding SelectedItem, Mode=TwoWay}" />

Adding controls dynamically in WPF MVVM

I am working on a dynamic search view wherein clicking a button should add a new row containing 3 combobox and 2 textboxes.
How should I go about doing this?
If you really want to do mvvm , try to forget "how can I add controls". You don't have to, just think about your viewmodels - WPF create the contols for you :)
In your case lets say we have a SearchViewModel and a SearchEntryViewmodel.
public class SearchEntryViewmodel
{
//Properties for Binding to Combobox and Textbox goes here
}
public class SearchViewModel
{
public ObservableCollection<SearchEntryViewmodel> MySearchItems {get;set;}
public ICommand AddSearchItem {get;}
}
Till now you dont have to think about usercontrols/view. In your SearchView you create an ItemsControl and bind the ItemsSource to MySearchItems.
<ItemsControl ItemsSource="{Binding MySearchItems}"/>
You see now all of your SearchEntryViewmodels in the ItemsControl(just the ToString() atm).
To fit your requirements to show every SearchEntryViewmodel with 3Comboboxes and so on you just have to define a DataTemplate in your Resources
<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
<StackPanel Orientation="Horizontal">
<Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
<!-- the other controls with bindings -->
</StackPanel>
</DataTemplate>
That's all :) and you never have to think about "how can I add controls dynamically?". You just have to add new SearchEntryViewmodel to your collection.
This approach is called Viewmodel First and I think it's the easiest way to do MVVM.
One option is that you can create TextBoxes and comboboxes in backend by creating a new instanse.
But the better option is that you can create one usercontrol which contains All texboxes and comboboxes which you want to add and in which format you want.
After creating when the button is pressed you can create a instace of this usercontrol and set it in the grid or any other control by using SetValue property of the control.
If you are new to WPF and MVVM this read this blogs to understand this.
https://radhikakhacharia.wordpress.com/2012/06/01/wpf-tutorial-3/
https://radhikakhacharia.wordpress.com/2012/02/13/model-view-viewmodel/
If you are new to both MVVM and WPF, there is a really wonderful video tutorial on how to
architect a C# / WPF / MVVM application by Jason Dollinger which is available here on lab49. All of the sourcecode he developes in this amazing video is available also right here on lab49.
After watching it, you will not have any problems developing your search view for sure.

How to enable wpf controls through data binding on a selected item from a combo box

I am looking for a way where a control can be enable when an item from a combo box is selected. Is there a simple way through data binding when a user selects an item from a combo box that it then enables another control to be used?
If you're using MVVM, you can bind the SelectedItem of the combobox to a property in your viewmodel.
Say this is your combobox:
<ComboBox ItemsSource="{Binding widgetlist}" SelectedItem="{Binding Path=selectedwidget, Mode=TwoWay}"></ComboBox>
And this is your control:
<DockPanel IsEnabled="{Binding controlenabled}">
...
</DockPanel>
Then in selectedwidget's setter, you can change the controlenabled property to False or True. Don't forget to notify that the controlenabled property changed (or if you want, make controlenabled a DependencyProperty.)
In summary, you've got 3 properties to bind to:
widgetlist, an ObservableCollection or some other collection that is the source for your combobox
selectedwidget, an item of that collection type that changes to whatever the combobox currently has selected
controlenabled, a bool that the other controls look at to decide if they are enabled/disabled.
Like many examples in MVVM, this way may require slightly more thought and code on the outset, but will be far more maintainable and scalable later. For example, say you want some more controls to also enable/disable themselves based on the same scenario. Piece of cake: add IsEnabled="{Binding controlenabled}"> to them.
Yes. You want to bind to IsEnabled in the target control which you want to dynamically enable or disable, and use a Value Converter to convert a matching string or item from the ComboBox to a true value for being enabled.

How to pass data between controls and persist the values in WPF

I am stuck on how to pass data from one control to another. If I have a listbox control and the Contol Item contains a datatemplate which renders out 5 fields ( first name, last name, email, phone and DOB) all of which come from an observable collection. How can I allow the user to select a listbox item and have the valuesbe stored within a new listbox control?
Is this done through the creation of a new collection or is there a more simple way to bind these values to a new control?
thank you,
If it is not too late, I would strongly recommend that you use the MVVM pattern. The problem you are facing is typical for WPF without a decent presentation model and wont be the last one.
Using MVVM you would pass data between controls/views through the ViewModel. In your example you would have a PersonViewModel with an ObservableCollection containing first name, last name, email and DOB. Additionally it would have a property SelectedItem. This property can be bound to in a lot of different controls/views without them having to know each other.
Let's say you have a:
<ListBox Name="DemoList" ItemsSource="{Binding ...}">
<ListBox.ItemTemplate>
...
</ListBox.ItemTemplate>
</ListBox>
And another control, maybe a TextBox:
<TextBox Text="I want to bind this to the Email property" />
You can achieve this pretty easily, with:
<TextBox Text="{Binding ElementName=DemoList, Path=SelectedItem.Email}" />
Note the ElementName property of the Binding. This allows you to bind relative to another control, and in this case you want the SelectedItem of your ListBox. SelectedItem will contain an element of the collection in the ItemsSource (or null if nothing is selected), so you can then bind to its properties.
It gets more complex if you want to support multiple selection, but it doesn't sound like this is a requirement for you.

WPF CheckBox IsChecked can't be reset when page(data source) is updated

I have question on the checkbox.
First of all,
I have a usercontrol which has a list box like this and this user control will be switched by 2 button and then the data source is changed and then the the displayed officer status will be changed:
When I check the checkbox, Officers[0].IsOnDuty will be changed to true.
The problem is:
When I click another button and switch to another data source, this checked check box is still checked but the Officers[0].IsOnDuty for this data source is false.
How to solve this?
The data context of the list box item is an item for your officers collection, not the collection itself. And using a one way binding is incorrect, as the data source (the officer) will not be updated. So change the DataTemplate to:
<CheckBox IsChecked="{Binding Path=IsOnDuty, Mode=TwoWay}" />
*Here is the list box xaml:
<ListBox ItemsSource="{Binding OfficersCollection}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=Officers[0].IsOnDuty, Mode=OneWay}" />
*
The problem with your approach is that once you change the ItemsSource (by switching to the next page) your chekcbox is still bound to the item of the first collection. I think this happens because you explicitly use an indexer for the binding Path=Officers[0].IsOnDuty
Your samplelist box xaml does not really make sense. the ItemsSoruce is a OfficerCollection and your ItemTemplate binds to a collection of Officers too. Depending on what you are trying to accomplish you should do one of the following:
If your are just interested in the first officer (as your sample suggest), add a DependencyProperty FirstOfficer (or a INotifyPropertyChanged) property to your collection and bind to it: IsChecked="{Binding Path=Officers.FirstOfficer, Mode=OneWay}"
If you however are interested in all Officers and want checkboxes for all of them you should create a DataTemplate for the Officer type and use this as the ItemTemplate.
Generally you can stay out of a lot of trouble if you stick with MVVM and really tailor your ViewModel objects very close to what the View needs so you can bind your View to the ViewModel in the simplest possible way. Think of the ViewModel as the View you want to build but without a visual representation.

Resources