Create UserControl WPF buttons for ListView - c#

I need help with buttons in list view. I am creating custom form for SCSM. List view is working without problems, but I need add there Add button, Open button and Delete button. Add button working without problem, but other buttons do nothing. Can anybody help me with it?
Thanks
XAML code is here:
<ListView Name="ListViewMonitor" VerticalAlignment="Top" HorizontalAlignment="Stretch" Margin="10,0,00,0" MinHeight="100" Grid.Column="0" Grid.Row="1" ItemsSource="{Binding Path=CustomRelatedMonitor, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ListView.View>
<GridView>
<GridViewColumn Header="{Binding Path=Strings[ID].Value, FallbackValue=ID, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type views:FormView}}}" DisplayMemberBinding="{Binding Path=ID}" Width="Auto"/>
<GridViewColumn Header="{Binding Path=Strings[CustomAssetStatus].Value, FallbackValue=CustomAssetStatus, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type views:FormView}}}" Width="Auto">
<GridViewColumn.CellTemplate>
<DataTemplate>
<smcontrols:ListPicker Name="listPickerAssetStatus" HorizontalAlignment="Stretch" Width="Auto" ParentCategoryId="{Binding Source=12435943-EBA1-3E78-BB6C-A731E44EDCFD, Mode=OneWay}" SelectedItem="{Binding Path=CustomAssetStatus, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<StackPanel Margin="10,0,10,0" Grid.Row="1" Grid.Column="1" VerticalAlignment="Top" HorizontalAlignment="Right">
<Button VerticalAlignment="Top" HorizontalAlignment="Right" Name="buttonAddMonitor" Height="20" Width="65" Content="{Binding Path=Strings[buttonAdd].value, FallbackValue=Add, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type views:FormView}}}" Click="buttonAddMonitor_Click" />
<Button VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,10,0,0" Name="buttonRemoveMonitor" Height="20" Width="65" IsEnabled="{Binding ElementName=ListViewMonitor, Path=SelectedItems.Count}" Content="{Binding Path=Strings[buttonRemove].value, FallbackValue=Remove, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type views:FormView}}}" Click="buttonRemoveMonitor_Click" />
<Button VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,10,0,0" Name="buttonOpenMonitor" Height="20" Width="65" IsEnabled="{Binding ElementName=ListViewMonitor, Path=SelectedItems.Count}" Content="{Binding Path=Strings[buttonOpen].value, FallbackValue=Open, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type views:FormView}}}" Click="buttonOpenMonitor_Click" />
</StackPanel>
Code for buttons:
public ListView ListViewAllMonitors { get; set; }
private ListView GetListView (string Name)
{
switch (Name)
{
case "buttonAddMonitor":
case "buttonRemoveMonitor":
case "buttonOpenMonitor":
{
return this.ListViewAllMonitors;
}
default:
{
throw new Exception(String.Format("ListView for control: {0}- not found", Name));
}
}
}
private void buttonAddMonitor_Click(object sender, RoutedEventArgs e)
{
ButtonAdd_Click(new Guid("DD3BDB96-BC9E-D46E-5847-BAB387039B36"), ListViewMonitor);
}
private void ButtonAdd_Click(Guid mpClassGuid, ItemsControl listView)
{
FormUtilities.Instance.LaunchAddInstancePickerDialog(listView.ItemsSource as Collection<IDataItem>, mpClassGuid);
}
private void buttonRemoveMonitor_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var CustomListView = GetListView(button.Name);
if (CustomListView == null) return;
var list = (IList<IDataItem>)CustomListView.ItemsSource;
if (list == null) return;
foreach (IDataItem item in new ArrayList(CustomListView.SelectedItems))
{
list.Remove(item);
}
}
private void buttonOpenMonitor_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var ListView = GetListView(button.Name);
if (ListView == null) return;
OpenInstance(ListView);
}
public void OpenInstance(ListView ListView)
{
if (ListView == null) return;
foreach (IDataItem dataItem in ListView.SelectedItems)
{
FormUtilities.Instance.PopoutForm(dataItem);
}
}

Related

Texbox value binding in WPF MVVM

I have sample XAML with TextBox code as:
XAML
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Center"
Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="0.5" Margin="0" Height="50" Background="Transparent" Foreground="White" />
<Button CommandParameter="{Binding ListExecActionId}"
Command="{Binding Source={StaticResource Locator}, Path=TaskPerformanceModel.ActivityAction_comment}"
Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
View Model:
public string Remarks
{
get { return _remarks; }
set
{
if (!string.Equals(_remarks, value))
{
_remarks = value;
RaisePropertyChanged("Remarks");
}
}
}
ActivityAction_coment as follows
public RelayCommand<object> ActivityAction_comment
{
get
{
if (_ActivityAction_comment == null)
{
_ActivityAction_comment = new RelayCommand<object>((ExecActionId) => ActivityComment(ExecActionId));
}
return _ActivityAction_comment;
}
}
private void ActivityComment(object _id)
{
try
{
using (DataContext objDataContext = new DataContext(DBConnection.ConnectionString))
{
ListExecutionAction tblListExec = objDataContext.ListExecutionActions.Single(p => p.Id == Convert.ToInt32(_id));
**tblListExec.Remarks = Remarks; // Not getting Remarks value from Textbox**
objDataContext.SubmitChanges();
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskExecution:ActivityComment");
}
}
I am unable to get textbox (Remarks) value in view model. Always getting "".
can any one help me out please.
For more clarity I am updating view:
<ListView.View>
<GridViewColumn >
<GridViewColumn.CellTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ActionDescription}" Foreground="White" FontSize="16"></TextBlock>
<ToggleButton Name="button">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<TextBlock>Remarks!!</TextBlock>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False" Width="250" Height="100">
<StackPanel>
<TextBlock Background="LightBlue" Text="{Binding ActionDescription}"></TextBlock>
<TextBlock Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Text="Comments:" Foreground="White" Background="Transparent" />
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Center"
Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}"
BorderThickness="0.5" Margin="0" Height="50"/>
<!--Text="{Binding Remarks, Mode=OneWayToSource}" Text="{Binding Path=Remarks, UpdateSourceTrigger=PropertyChanged}" DataContext="{Binding CollectionOfListQueue}" Background="Transparent" Foreground="White"-->
<Button CommandParameter="{Binding ListExecActionId}" Command="{Binding Source={StaticResource Locator}, Path=TaskPerformanceModel.ActivityAction_comment}" Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
<Button Content="Cancel" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="2,0,0,0" Height="Auto" />
<!--</Grid>-->
</StackPanel>
</Popup>
</StackPanel>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
Bind to ActivityAction_comment and Remarks properties of the view model:
<Button CommandParameter="{Binding ListExecActionId}"
Command="{Binding DataContext.ActivityAction_comment, RelativeSource={RelativeSource AncestorType=ListView}}"
Content="Save" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="3,0,0,0" Height="Auto" />
You need to the same for the Remarks binding
<TextBox Text="{Binding DataContext.Remarks, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=ListView}}" ... />
You should then be able to get the value in the TextBox using the Remarks source property:
private void ActivityComment(object _id)
{
try
{
using (DataContext objDataContext = new DataContext(DBConnection.ConnectionString))
{
ListExecutionAction tblListExec = objDataContext.ListExecutionActions.Single(p => p.Id == Convert.ToInt32(_id));
string remarks = Remarks;
objDataContext.SubmitChanges();
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message, "TaskExecution:ActivityComment");
}
}

Combobox default value for new item

I have 2 comboboxs that has it's itemssource bound to 2 lists which are in a listview. This all works fine however when I add a new new item to the list the combobox values are blank and I want them to show me "All Zones" for one and "All Facies" in the other. How do I get this to work? I have tried many examples but all want me to use the "IsSynchronizedWithCurrentItem" to be true or the SelectedIndex to 0 however this also sets the current combobox values to the SelectedIndex which is not what I want I only want it if the combobox is blank. Can anyone please help me?
Combobox's inside the ListView
<GridViewColumn Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Style="{DynamicResource ComboBoxStyle1}" x:Name="zoneComboBox" Margin="0,0,5,0" Height="20" Width="80" ItemsSource="{Binding DataContext.Zones, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, Mode=FindAncestor}}" SelectedValue="{Binding Zone}" SelectedIndex="0"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
<GridViewColumnHeader>
<TextBlock Text="Zones" FontFamily="{DynamicResource FontFamily}" FontSize="11" FontWeight="Bold"/>
</GridViewColumnHeader>
</GridViewColumn>
<GridViewColumn Width="100">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox Style="{DynamicResource ComboBoxStyle1}" x:Name="faciesComboBox" Margin="0,0,5,0" Height="20" Width="80" ItemsSource="{Binding DataContext.Facies, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, Mode=FindAncestor}}" SelectedValue="{Binding Facie}" SelectedIndex="0"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
<GridViewColumnHeader>
<TextBlock Text="Facies" FontFamily="{DynamicResource FontFamily}" FontSize="11" FontWeight="Bold"/>
</GridViewColumnHeader>
</GridViewColumn>
Add new rule method
private void AddRuleBtn_Click(object sender, RoutedEventArgs e)
{
rules.Add(new GeologicalAnalysisRule());
}
Observable Collection (Edit)
private ObservableCollection<GeologicalAnalysisRule> rules;
public RuleSetterControl()
{
InitializeComponent();
Rules = new ObservableCollection<GeologicalAnalysisRule>();
Rules.Add(new GeologicalAnalysisRule());
}
public ObservableCollection<GeologicalAnalysisRule> Rules
{
get { return rules; }
set
{
if (Equals(value, rules)) return;
rules = value;
OnPropertyChanged();
}
}
Instead of using private variable rules use Property Rules in the button click event.
private void AddRuleBtn_Click(object sender, RoutedEventArgs e)
{
Rules.Add(new GeologicalAnalysisRule());
}

Observablecollection.RemoveAt(item) doesn't refresh UI

I have an ObservableCollection<MyType>, where MyType implements INotifyPropertyChanged using Fody.
This collection was binded to my ui as this
<Grid x:Name="DetallePresupuesto" Grid.Row="2">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Text="{x:Static resources:Labels.SALUD_DetallePresupuesto}" Background="Bisque" TextAlignment="Center"/>
<DataGrid
x:Name="DetallePresupuestoGrid"
Grid.Row="1"
Grid.ColumnSpan="1"
AutoGenerateColumns="False"
Style="{DynamicResource ParadigmaNDataGrid}"
ItemsSource="{Binding Path=DetallePresupuesto,UpdateSourceTrigger=PropertyChanged}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventToCommand Command="{Binding ItemSelectionChangedCommand}" CommandParameter="{Binding ElementName=DetallePresupuestoGrid, Path=SelectedItem}"/>
</i:EventTrigger>
<i:EventTrigger EventName="AddingNewItem">
<cmd:EventToCommand Command="{Binding InsertItemCommand}" PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Columns>
<DataGridTemplateColumn Header="{x:Static resources:Labels.GENERAL_Item}" Width="10*" ClipboardContentBinding="{x:Null}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Merlin_ConceptosFacturacion.StrDescripcionConcepto}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<controls:Search SearchParms="{Binding ElementName=EstaVentana,Path=DataContext.BusqItems}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="{x:Static resources:Labels.GENERAL_Cantidad}" Width="2*" Binding="{Binding Path=NumCantidad}" ClipboardContentBinding="{x:Null}"/>
<DataGridTextColumn Header="{x:Static resources:Labels.GENERAL_ValorUnitario}" Width="2.5*" Binding="{Binding Path=NumValorFacturacionDigitado}" ClipboardContentBinding="{x:Null}"/>
<DataGridTextColumn Header="{x:Static resources:Labels.GENERAL_ValorTotal}" Width="2.5*" Binding="{Binding Path=NumValor}" ClipboardContentBinding="{x:Null}"/>
<DataGridTemplateColumn Width="70" Header="{x:Static resources:Labels.GENERAL_BorrarItem}" HeaderStyle="{StaticResource ResourceKey=ParadigmaNDataGridHeaderStyle}">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Style="{StaticResource InLineDeleteButton}" Command="{Binding Path=DataContext.DeleteCommand, ElementName=EstaVentana}" CommandParameter="{Binding ElementName=DetallePresupuestoGrid,Path=SelectedItem}" Visibility="{Binding Merlin_ConceptosFacturacion.NumIdConcepto,Converter={cnv:decimalToVisibilityConverter}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
private ObservableCollection<MyType> _DetallePresupuesto;
public ObservableCollection<MyType> DetallePresupuesto
{
get {
if (_DocumentoPresupuesto == null)
return new ObservableCollection<MyType>();
else
return new ObservableCollection<MyType>(_DocumentoPresupuesto.Parent.MyType);
}
set { SetProperty(ref _DetallePresupuesto, value); }
}
And this command that deletes one row each time
public void ExecuteDelete(object p)
{
try
{
bool borro = false;
MyType det = (MyType)p;
MyType item = DetallePresupuesto.Where(x => x.NumIdTransaccion == det.NumIdTransaccion).FirstOrDefault();
if (item != null)
{
DetallePresupuesto.RemoveAt(DetallePresupuesto.IndexOf(item));
db.SetEntityState(det, EntityState.Deleted);
db.SaveEntity(det);
}
}
catch (Exception e)
{
ReportarInconsistencia(e.Message);
}
}
My problem is when delete an item from the collection id does it but it doesn't refresh the UI.
How can I Do to force de UI refresh ?
You're not binding to DetallePresupuesto in the UI. You are binding to either:
return new ObservableCollection<MyType>();
or
return new ObservableCollection<MyType>(_DocumentoPresupuesto.Parent.MyType);
For the UI to be updated you need to let the property return the list that you are removing from, i.e. the DetallePresupuesto. That means the getter should look something like this.
public ObservableCollection<MyType> DetallePresupuesto
{
get {
if (_DetallePresupuesto == null)
_DetallePresupuesto = new ObservableCollection<MyType>(); //populate here
return _DetallePresupuesto;
}
}
Also, try to avoid setters for your collections.

Live Filtering in DataGrid using TextBox

Ihave a textbox and a DataGrid. When I type in something in textbox, I want to filter the data in DataGrid.
I have done that with the below mentioned code:
In XAML:
<CollectionViewSource x:Key="GroupsViewSource" Source="{Binding Groups, UpdateSourceTrigger=PropertyChanged}" Filter="CollectionViewSource_Filter">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="GroupName"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<DataGrid Grid.Row="5" Grid.Column="1" ItemsSource="{Binding Source={StaticResource GroupsViewSource}}"
SelectedItem="{Binding SelectedGroup}"
AutoGenerateColumns="False" CanUserAddRows="False"
SelectionMode="Single" SelectionUnit="FullRow"
EnableRowVirtualization="False" VirtualizingPanel.IsContainerVirtualizable="False" RowEditEnding="DataGrid_RowEditEnding">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Group Name" Width="*" SortMemberPath="GroupName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding GroupName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding GroupName}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Parent Group" Width="*" SortMemberPath="ParentID">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ParentID, Converter={StaticResource parentIDToGroupNameConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Source={StaticResource ParentGroupsViewSource}}"
DisplayMemberPath="GroupName"
SelectedValue="{Binding ParentID, Converter={StaticResource parentIDToGroupNameConverter}}" SelectedValuePath="GroupName"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Edit" Width="50" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="btnEdit" Style="{StaticResource ResourceKey=EditButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityInverseConverter}}"
Click="EditSaveButton_Click"
Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
<Button x:Name="btnSave" Grid.Row="1" Style="{StaticResource ResourceKey=SaveButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityConverter}}"
Click="EditSaveButton_Click"
Command="{Binding DataContext.SaveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delete" Width="70" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="btnDelete" Style="{StaticResource ResourceKey=DeleteButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityInverseConverter}}"
Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
<Button x:Name="btnCancel" Grid.Row="1" Style="{StaticResource ResourceKey=CancelButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityConverter}}"
Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<TextBox Grid.Column="0" Text="{Binding SearchGroupName, UpdateSourceTrigger=PropertyChanged}" />
In CodeBehind:
private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
var a = e.Item.GetType().GetProperty("GroupName");
if (a != null)
{
if (_viewModel.SearchGroupName != "")
{
var s = a.GetValue(e.Item, null);
if (s != null)
e.Accepted = s.ToString().Contains(_viewModel.SearchGroupName, StringComparison.OrdinalIgnoreCase);
else
e.Accepted = false;
}
else
e.Accepted = true;
}
}
In ViewModel:
ERPLiteDBContext db = new ERPLiteDBContext();
public ListViewModel()
{
Groups = new ObservableCollection<Group>(db.Groups);
SearchGroupName = "";
}
private string _searchGroupName;
public string SearchGroupName
{
get
{
return _searchGroupName;
}
set
{
_searchGroupName = value;
OnPropertyChanged("SearchGroupName");
}
}
private ObservableCollection<Group> _groups;
public ObservableCollection<Group> Groups
{
get
{
return _groups;
}
set
{
_groups = value;
OnPropertyChanged("Groups");
}
}
The above code works. But for above code to work, I have to type-in something into the textBox, then click on the header of the DataGrid to sort it. So, in short above code does not provide live filtering. I would like to filter my data when I type-in something in TextBox......
So the filtering in your code is actually a follow-up from sorting. To perform filtering whenever you like, I suggest following, making small changes to your viewmodels:
Group knows wether itself should be filtered or not. It has a IsHidden property:
public class Group // actually a viewmodel
{
public bool IsHidden
{
get;
set;
}
public string Name
{
get;
set;
}
...
}
IsHidden is set for each member in the collection, each time the Text changes. The CollectionViewSource checks this property:
private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
// reset first to keep continious filtering
Groups.ToList().ForEach(i => i.IsHidden = false);
foreach (var filteredGroup in Groups.Where(vm => vm.Name == _viewModel.SearchGroupName))
{
filteredGroup.IsHidden = true;
}
ICollectionView cv = CollectionViewSource.GetDefaultView(_dataGrid.ItemsSource);
if (cv != null)
{
// filter the Groups collection
cv.Filter = (vm as Group) => vm.IsHidden == false;
}
}

How to verify a string changed from a textbox in listview is not the same as any exiting ones

I have a ListView box containing TextBoxes that allow users to add and change the content. How do I verify that the content that is changed is not the same as any exiting one in C# behind?
Xaml:
<ListView
x:Name="_regionQueryListBox"
Width="122"
HorizontalAlignment="Left"
VerticalAlignment="Stretch"
DataContext="{Binding}"
IsSynchronizedWithCurrentItem="True"
Style="{StaticResource ListViewRegionSelectorStyle}"
ItemsSource="{Binding Path=Model}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectionChanged="_regionQueryListBox_SelectionChanged">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="Region" Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}}">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox
HorizontalAlignment="Left"
VerticalAlignment="Stretch"
MaxLength="16"
Width="110"
Margin="-2,0,0,0"
Padding="-2,0,0,0"
Text="{Binding Path=RegionName}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Yes, it is MVVM. I have a validation for adding same item and you can find the Model like below:
private void OnQueryCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
if (Model.Count == 0)
{
CurrentRegionViewModel = null;
}
if (args.Action == NotifyCollectionChangedAction.Add)
{
RegionQuery addedRegionQuery = args.NewItems.OfType<RegionQuery>().FirstOrDefault();
if (addedRegionQuery != null)
{
string name = addedRegionQuery.RegionName;
while (Model.Any(q => q.RegionName == name && q != addedRegionQuery))
{
name += "*";
}
addedRegionQuery.RegionName = name;
}
}

Categories