Select Multiple items in listbox in wpf using c# - c#

I want to set multiple selection in a ListBox using c#.
For example, I have a list of values I want to set these values as selected in the ListBox.
How can I do this?

MyListBox.SelectedItems.Add(item1);
MyListBox.SelectedItems.Add(item2);
.....

You did not explain much, hopefully your are doing this the WPF way...
Create an IsSelected property on your data items then give the style to your ListBoxItems that selects them whenever the IsSelected is enabled:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
Then change the property on your data items, and raise the OnPropertyChanged event.

Related

MVVM - Hide Datagrid column based on column name with autogeneratecolumns = True

I have a DataGrid that's bound to Datatable, and I want to uniquely identify rows in the DataTable using the ID, but I don't want it to be shown in the DataGrid
What I reached so far by searching and excluding:
Data columns are not predefined, so, I have to use AutoGenerateColumns=True, hence, I can't define the columns manually and set the Visibility property to False.
I can't use List or ObservableCollection to define private ID member, because the data are dynamic.
I am following MVVM so, I can't use AutoGeneratingColumns event handler directly and can't expose the View to the ViewModel.
The closest I get to an answer is using DataTrigger to set Visibility to False using CellStyle, but it just hid the cells, not the entire column, and I also tried it for DataGridColumnHeader and it didn't work:
code:
<Style x:Key="ColumnStyle" TargetType="DataGridColumnHeader">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Value}" Value="id">
<Setter Property="Visibility" Value="Hidden"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
How to do it while maintaining the previous conditions?
Thanks in advance
EDIT:
I fixed the code for DataGridColumnHeader using Path=Column.Header which doesn't make sense to me but it's irrelevant; Still, there and empty column standing there, with no idea how to remove it.
It sounds like you want to track the selected Item. If you want to track the "selected Element", you have to use a CollectionView.
WPF controls do not direcly bind to collections. They bind to a CollectionView. And if you do not give them one, they will create one themself from whatever collection you hand them. If you want sorting, filtering, ordering and selection tracking, CollectionView is the droid you are looking for:
https://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.aspx
Just take control of it's creation and expose it (rather then the raw collection).
I found a solution by applying this style:
<Style x:Key="ColumnStyle" TargetType="DataGridColumnHeader">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=Value}" Value="id">
<Setter Property="Visibility" Value="Hidden"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
to DataGridCell and to DataGridColumnHeader and allocating the column in the end of the table this removed the empty column from the middle of the table.

Call an event based on property value in WPF

I have a DataGrid and a button. I want to enable the button only when an entire row is selected. Otherwise it should be disabled.
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
//Here I want to enable the button which is outside the grid.
</Trigger>
</Style.Triggers>
</Style>
How can I do it?
I am not sure whether using a style trigger is a correct idea to solve your problem.
This issue can be solved using a delegate-event concept in your view model.
Create a property in your datagrid item source whose change raises an event. The handler of the event will in turn would set the button IsEnable property to true/false.
I have created a test application that would help you understand what I want to say.
Download it from : https://www.dropbox.com/s/hxzmpslt1bs0sei/WpfApplication2.rar?dl=0
try this and tell me if it did what you desired.

WPF: databinding to ListView so that listview item's ForeColor reflects bool property value changes

WPF application, .NET 3.5.
I have a ListView control, to which I bind a collection of business classes.
I'd like to bind the ForeColor of items to a bool property of the class (say: MyClass.Active), so that the items are displayed in black when active, in light gray when disabled.
I want listview items to change their color on-the-fly, I mean when I'd change Active value of one of the instances in my databound collection, its respective listview item would change its color automatically.
What do I need to achieve this? I've found numerous tutorials on WPF databinding on the net, some questions on StackOverflow, but not exactly the same thing, and I don't want to start combining my solution out of everything I can put my hands on, by trial and error.
I know about INotifyPropertyChanged (for my business class), IValueConverter (but should I need it for a bool??), DataTrigger etc.
But which pieces of the puzzle do I really need, what is the simpliest way to achieve my goal?
I would just do it in a style, and apply that style on your List items. Providing that your object implements INotifyPropertyChanged and the property changed event gets raised when IsActive changes, this will change the foreground to Gray if IsActive = False
<Style x:Key="DisableInactiveTextStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="Black" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsActive}" Value="False">
<Setter Property="Foreground" Value="LightGray" />
</DataTrigger>
</Style.Trigger>
</Style>
<TextBlock Style="{StaticResource DisableInactiveTextStyle}" ... />
I would suggest creating an IValueConverter that takes a bool and returns a color. You can then bind the ForeColor to the MyClass.Active property and use the created converter.

Combobox DropDownOpened event

I have a combo box inside a list view. And different items (rows) in the list view need to display (based on some condition) one among 3 sets of combo box items in the respective combo box which is . Right now I am achieving this by using 3 data templates bound to 3 different properties of List<string>. I am hooking up the appropriate data templates during the DropDownOpened event of the combo boxes.
The problem that I am facing is that I am having to click the combo box twice each time to have it dropped down. I did a Debug.WriteLine() to see if my first click does the job of selecting a data template, I found that it indeed does. But just that it does not drop down at the first click itself.
I guess this is because I am changing the data template after the combo box has dropped down its popup and hence it refreshes again whose results are furnished only after I perform the second click.
My question is whether there is any other way of accomplishing what I am trying or do I have to make any changes in my existing DropDownOpened event handler.
Please suggest.
EDIT : I'm using WPF
Thanks
Would it be an option to use styles to set the items? e.g.
<ComboBox>
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding SomeConditionalProperty}"
Value="SomeConditionalValue">
<Setter Property="ItemsSource" Value="{BindingToFindRightItems}"/>
</DataTrigger>
<DataTrigger Binding="{Binding SomeConditionalProperty}"
Value="AnotherValue">
<Setter Property="ItemsSource" Value="{BindingToFindRightItemsForAnotherValue}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>

WPF Databinding and Styling based on Data in an item in an IList

I have a ListBox bound to a list of Items (for arguement, lets say its got a string and two dates Entered and Done).
I would like to make the background color of items in the ListBox have a gray color if the Done DateTime is != DateTime.MinValue.
Edit:
Should I make a converter? and convert DateTime to a Brush based on the value of the DateTime?
Is something like this my best option? or is there a simple Xaml snippet I could use?
[ValueConversion(typeof(DateTime), typeof(Brush))]
class MyConverter : IValueConverter
{
...
}
A ValueConverter would work. Another option would be to use a DataTrigger in the style of ListBoxItem. Maybe something like this:
<Style x:Name="MinDateTimeListBoxStyle" TargetType="ListBoxItem">
<Style.Triggers>
<Setter Property="Background" Value="Gray" />
<DataTrigger Binding="{Binding Path=Done}"
Value="{x:Static sys:DateTime.MinValue}">
<Setter Property="Background" Value="White" />
</DataTrigger>
</Style.Triggers>
</Style>
This will set the background to Gray when the value of Done isn't DateTime.MinValue. I don't think there is a way to do a not equals comparison in a trigger, so it sets the background to Gray by default, and only changing it back to white if Done hasn't changed yet. It would probably be better to use the correct color for the background instead of white (maybe get the value of the parent's background?), but this should give you something to start with.
Update: To apply this style to the items of only certain ListBoxes, give the style a name and set the ItemContainerStyle as appropriate:
<ListBox x:Name="StyledListBox"
ItemContainerStyle="{StaticResource MinDateTimeListBoxStyle}" />
<ListBox x:Name="NormalListBox" />

Categories

Resources