There is an Observablecollection Fathers that stores the ID-Firstname-Lastname father. How to make it so that when loading data from the child.lbs file, the ID value that is written in the file under word[4] is selected in the Combobox field? Item values are spelled out using XAML <Combobox "ItemsSource = {Binding Fathers}"/>
That is, so that when the file is loaded, the same values are restored as they were before the shutdown (the so-called Save/Load)
enter image description here
enter image description here
Father.cs
namespace LabelBase.Models
{
public class Father : INotifyPropertyChanged
{
private int _id;
public int FatherID
{
get => _id;
set
{
_id = value;
OnPropertyChanged();
}
}
private string _firstname;
public string Firstname
{
get => _firstname;
set
{
_firstname = value;
OnPropertyChanged();
}
}
private string _secondname;
public string Secondname
{
get => _secondname;
set
{
_secondname = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
Child.cs
namespace LabelBase.Models
{
public class Child : INotifyPropertyChanged
{
private int _id;
public int ChildID
{
get => _id;
set
{
_id = value;
OnPropertyChanged();
}
}
private string _first;
public string Firstname
{
get => _first;
set
{
_first = value;
OnPropertyChanged();
}
}
private string _second;
public string Secondname
{
get => _second;
set
{
_second = value;
OnPropertyChanged();
}
}
private Father _father;
public Father Father
{
get => _father;
set
{
_father = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
child.lbs contents:
13;Ken;Hollow;83
10;Fill;Kenory;93
father.lbs contents:
83;Frank;Malkov
93;Jack;Miles
MainWindow.xaml:
<Grid>
<TabControl>
<TabItem Header="Save">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0" Content="Save" Margin="100" Height="50" Command="{Binding SaveButton}"/>
<Button Grid.Column="1" Content="Load" Margin="100" Height="50" Command="{Binding LoadButton}"/>
</Grid>
</TabItem>
<TabItem Header="Child">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Margin="5,5,5,50" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Height="25" Margin="5" Text="{Binding ElementName=ChildGrid, Path=Columns[0].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBlock Grid.Column="0" Grid.Row="1" Height="25" Margin="5" Text="{Binding ElementName=ChildGrid, Path=Columns[1].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBlock Grid.Column="0" Grid.Row="2" Height="25" Margin="5" Text="{Binding ElementName=ChildGrid, Path=Columns[2].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBlock Grid.Column="0" Grid.Row="3" Height="25" Margin="5" Text="{Binding ElementName=ChildGrid, Path=Columns[3].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBox Grid.Column="1" Grid.Row="0" Height="25" Text="{Binding SelectedChildren.ChildID}" Margin="5"/>
<TextBox Grid.Column="1" Grid.Row="1" Height="25" Text="{Binding SelectedChildren.Firstname}" Margin="5"/>
<TextBox Grid.Column="1" Grid.Row="2" Height="25" Text="{Binding SelectedChildren.Secondname}" Margin="5"/>
<ComboBox Grid.Column="1" Grid.Row="3" Height="25" ItemsSource="{Binding Fathers}" SelectedItem="{Binding SelectedChildren.Father}" Margin="5">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="Firstname"/>
<Binding Path="Secondname"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
<DataGrid Name="ChildGrid" Grid.Column="1" Margin="0,10,10,10" AutoGenerateColumns="False" ItemsSource="{Binding Children}" SelectedItem="{Binding SelectedChildren}">
<DataGrid.Columns>
<DataGridTextColumn Width="auto" Header="ID" Binding="{Binding ChildID}"/>
<DataGridTextColumn Width="auto" Header="Firstname" Binding="{Binding Firstname}"/>
<DataGridTextColumn Width="auto" Header="Secondname" Binding="{Binding Secondname}"/>
<DataGridTextColumn Width="auto" Header="Father" Binding="{Binding Father.FatherID}"/>
</DataGrid.Columns>
</DataGrid>
<Button Height="25" Margin="10,0,10,20" Content="Add Child" Command="{Binding AddChildButton}" VerticalAlignment="Bottom"/>
</Grid>
</TabItem>
<TabItem Header="Father">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid Margin="5,5,5,50" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Height="25" Margin="5" Text="{Binding ElementName=FatherGrid, Path=Columns[0].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBlock Grid.Column="0" Grid.Row="1" Height="25" Margin="5" Text="{Binding ElementName=FatherGrid, Path=Columns[1].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBlock Grid.Column="0" Grid.Row="2" Height="25" Margin="5" Text="{Binding ElementName=FatherGrid, Path=Columns[2].Header, StringFormat={}{0}: }" TextAlignment="Right"/>
<TextBox Grid.Column="1" Grid.Row="0" Height="25" Text="{Binding SelectedFathers.FatherID}" Margin="5"/>
<TextBox Grid.Column="1" Grid.Row="1" Height="25" Text="{Binding SelectedFathers.Firstname}" Margin="5"/>
<TextBox Grid.Column="1" Grid.Row="2" Height="25" Text="{Binding SelectedFathers.Secondname}" Margin="5"/>
</Grid>
<DataGrid Name="FatherGrid" Grid.Column="1" Margin="0,10,10,10" AutoGenerateColumns="False" ItemsSource="{Binding Fathers}" SelectedItem="{Binding SelectedFathers}">
<DataGrid.Columns>
<DataGridTextColumn Width="auto" Header="ID" Binding="{Binding FatherID}"/>
<DataGridTextColumn Width="auto" Header="Firstname" Binding="{Binding Firstname}"/>
<DataGridTextColumn Width="auto" Header="Secondname" Binding="{Binding Secondname}"/>
</DataGrid.Columns>
</DataGrid>
<Button Height="25" Margin="10,0,10,20" Content="Add Father" Command="{Binding AddFatherButton}" VerticalAlignment="Bottom"/>
</Grid>
</TabItem>
</TabControl>
</Grid>
ContextVIew.cs:
using LabelBase.Models;
namespace LabelBase
{
public class ContextView : INotifyPropertyChanged
{
public ObservableCollection<Father> Fathers { get; }
public ObservableCollection<Child> Children { get; }
private Father _selectedFather;
public Father SelectedFathers
{
get => _selectedFather;
set
{
_selectedFather = value;
OnPropertyChanged();
}
}
private RelayCommand _addFatherButton;
public RelayCommand AddFatherButton
{
get
{
return _addFatherButton ?? (_addFatherButton = new RelayCommand(obj =>
{
Father f = new Father();
Random r = new Random();
f.FatherID = r.Next(99);
Fathers.Insert(Fathers.Count, f);
SelectedFathers = f;
}));
}
}
private Child _selectedChild;
public Child SelectedChildren
{
get => _selectedChild;
set
{
_selectedChild = value;
OnPropertyChanged();
}
}
private RelayCommand _addChildButton;
public RelayCommand AddChildButton
{
get
{
return _addChildButton ?? (_addChildButton = new RelayCommand(obj =>
{
Child c = new Child();
Random r = new Random();
c.ChildID = r.Next(99);
Children.Insert(Children.Count, c);
SelectedChildren = c;
}));
}
}
private RelayCommand _save;
public RelayCommand SaveButton
{
get
{
return _save ?? (_save = new RelayCommand(obj =>
{
StreamWriter swChild = new StreamWriter($"{AppDomain.CurrentDomain.BaseDirectory}/save/child.lbs", false);
StreamWriter swFather = new StreamWriter($"{AppDomain.CurrentDomain.BaseDirectory}/save/father.lbs", false);
foreach(Child item in Children)
{
string sandwich = $"{item.ChildID};{item.Firstname};{item.Secondname};{item.Father.FatherID}";
swChild.WriteLine(sandwich);
}
swChild.Close();
foreach (Father item in Fathers)
{
string sandwich = $"{item.FatherID};{item.Firstname};{item.Secondname}";
swFather.WriteLine(sandwich);
}
swFather.Close();
MessageBox.Show("Complete");
}));
}
}
private RelayCommand _load;
public RelayCommand LoadButton
{
get
{
return _load ?? (_load = new RelayCommand(obj =>
{
StreamReader srChild = new StreamReader($"{AppDomain.CurrentDomain.BaseDirectory}/save/child.lbs", false);
StreamReader srFather = new StreamReader($"{AppDomain.CurrentDomain.BaseDirectory}/save/father.lbs", false);
string lineChild, lineFather;
while((lineFather = srFather.ReadLine()) != null)
{
string[] word = lineFather.Split(';');
Father f = new Father();
f.FatherID = int.Parse(word[0]);
f.Firstname = word[1];
f.Secondname = word[2];
Fathers.Insert(Fathers.Count, f);
}
while((lineChild = srChild.ReadLine()) != null)
{
string[] word = lineChild.Split(';');
Child c = new Child();
c.ChildID = int.Parse(word[0]);
c.Firstname = word[1];
c.Secondname = word[2];
//c.Father.FatherID = int.Parse(word[3]);
Children.Insert(Children.Count, c);
}
srChild.Close();
MessageBox.Show("Complete");
}));
}
}
public ContextView(){
Fathers = new ObservableCollection<Father>();
Children = new ObservableCollection<Child>();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
}
There is a Project: https://github.com/RodKingroo/FatherChild
Who will help, thanks :)
Thanks, #BionicCode 4 ur help
Answer ContextWiew.cs:
using (StreamReader srChild = new StreamReader($"{AppDomain.CurrentDomain.BaseDirectory}/save/child.lbs")) {
lineChild = srChild.ReadLine();
while ((lineChild = srChild.ReadLine()) != null)
{
string[] word = lineChild.Split(';');
Child c = new Child();
c.ChildID = int.Parse(word[0]);
c.Firstname = word[1];
p.Secondname = word[2];
foreach (Father item in Father)
{
if (item.FatherID == int.Parse(word[5])) p.Father = item;
}
Children.Add(c);
SelectedChildren = c;
}
srChild.Close();
}
Related
I am using below code and MVVM observable, but "Clear" button not clears the content of text boxes.
What I need to do here?
MainWindow.xaml
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30*"/>
<RowDefinition Height="10*"/>
</Grid.RowDefinitions>
<Grid>
<ListView ItemsSource="{Binding Credentials, Mode=OneWay}">
<ListView.View>
<GridView>
<GridViewColumn Header="User Name">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding UserName}" Width="100"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Password">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Password}" Width="100"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
<Grid Grid.Row="1" >
<Button Grid.Column="0" Content="Clear" Command="{Binding ClearTextBoxCommand}" Width="150"/>
</Grid>
</Grid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
MyViewModel.cs
public class MyViewModel : INotifyPropertyChanged
{
private ObservableCollection<Credential> _credentials;
public RelayCommand ClearTextBoxCommand { get; }
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
var handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ObservableCollection<Credential> Credentials
{
get => _credentials;
set
{
if (value == _credentials)
return;
_credentials = value;
OnPropertyChanged();
}
}
public MyViewModel()
{
var data = new List<Credential> {new Credential {UserName = "user1", Password = "password1"}};
_credentials = new ObservableCollection<Credential>(data);
ClearTextBoxCommand = new RelayCommand(ClearTextBox);
}
private void ClearTextBox()
{
var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
_credentials = new ObservableCollection<Credential>(data);
MessageBox.Show("clear done!");
}
}
public class Credential
{
public string UserName { get; set; }
public string Password { get; set; }
}
Credentials property has notification about change in setter:
public ObservableCollection<Credential> Credentials
{
get => _credentials;
set
{
if (value == _credentials)
return;
_credentials = value;
OnPropertyChanged();
}
}
so if you need to change that collection, use property, not _credentials field
not _credentials = new ObservableCollection<Credential>(data);, but
private void ClearTextBox()
{
var data = new List<Credential> { new Credential { UserName = "", Password = "" } };
Credentials = new ObservableCollection<Credential>(data);
MessageBox.Show("clear done!");
}
Using the Credentials property instead of _credentials field is mandatory. But you do not have to assign a complete new ObservableCollection. Just clear the old one and add a new Credentials object.
private void ClearTextBox()
{
Credentials.Clear();
Credentials.Add(new Credential { UserName = "", Password = "" });
MessageBox.Show("clear done!");
}
This is working at my Application
View:
<UserControl x:Class="PRWSolution.UI.View.MachineView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:PRWSolution.UI.View"
xmlns:language="clr-namespace:PRWSolution.UI.Properties.Langs"
xmlns:setting="clr-namespace:PRWSolution.UI.Properties"
mc:Ignorable="d"
DataContext="{Binding Machine, Source={StaticResource Locator}}"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
Background="{DynamicResource MaterialDesignPaper}"
TextElement.FontWeight="Medium"
TextElement.FontSize="14"
FontFamily="{materialDesign:MaterialDesignFont}">
<Grid>
<StackPanel Orientation="Vertical">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.ColumnSpan="2">
<!--Toolbar for interaction-->
<ToolBarTray Grid.Column="0" Margin="0,5,0,0">
<ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
<Button x:Name="SaveMachine" ToolTip="Save" Command="{Binding SaveCommand, Mode=OneWay}">
<materialDesign:PackIcon Kind="ContentSave" />
</Button>
<Button x:Name="EditeMachine" ToolTip="Edit" Command="{Binding UpdateCommand, Mode=OneWay}">
<materialDesign:PackIcon Kind="Edit" />
</Button>
<Button x:Name="DeleteMachine" ToolTip="Delete" Command="{Binding DeleteCommand, Mode=OneWay}">
<materialDesign:PackIcon Kind="Delete" />
</Button>
<Separator />
<Button x:Name="ClearForm" ToolTip="Clear Form">
<materialDesign:PackIcon Kind="LayersClear" />
</Button>
</ToolBar>
</ToolBarTray>
<ToolBarTray Grid.Column="1" HorizontalAlignment="Right" Margin="0,5,0,0">
<ToolBar Style="{DynamicResource MaterialDesignToolBar}" ClipToBounds="False">
<Button x:Name="ExportMachine" ToolTip="Export" Click="ExportMachine_Click">
<materialDesign:PackIcon Kind="TableExport" />
</Button>
</ToolBar>
</ToolBarTray>
</Grid>
</Grid>
<!--Card for input database information-->
<materialDesign:Card Margin="5">
<StackPanel>
<!--Expander general machine information-->
<Expander Header="{x:Static language:Lang.ExpMachineData }" FontSize="11" HorizontalAlignment="Stretch" Margin="5,5,5,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtMachineID" Text="{Binding MachineID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgMachineID}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtCustomerID" Text="{Binding CustomerID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCustomerId}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
</StackPanel>
</Grid>
<Grid Grid.Column="1">
<StackPanel Orientation="Vertical">
<ComboBox x:Name="cmbCustomerName" Width="300" HorizontalAlignment="Left" SelectedValuePath="ClientName" SelectedValue="{Binding CustomerName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding MachineCustomer.ClientDataContext, Source={StaticResource Locator}}" DisplayMemberPath="ClientName" materialDesign:HintAssist.Hint="Customer Name" Margin="5"/>
<TextBox x:Name="txtCity" Text="{Binding City, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCity}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtCountry" Text="{Binding Country, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgCountry}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
</StackPanel>
</Grid>
</Grid>
</Expander>
<Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />
<!--Expander general part info-->
<Expander Header="Part Information" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtPartName" Text="{Binding PartName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Name" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtPartNumber" Text="{Binding PartNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Part Number" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtProject" Text="{Binding Project, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="Project" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
</StackPanel>
</Grid>
</Grid>
</Expander>
<Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />
<!--Expander for Machine Serials-->
<Expander Header="{x:Static language:Lang.ExpMachineSerials}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtSpindleC1" Text="{Binding SpindleC1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC1}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtSpindleC2" Text="{Binding SpindleC2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgSpindleC2}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtHoningHead" Text="{Binding HoningHead, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHoningHead}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
</StackPanel>
</Grid>
</Grid>
</Expander>
<Border Background="{DynamicResource MaterialDesignDivider}" Height="1" HorizontalAlignment="Stretch" SnapsToDevicePixels="True" />
<!--Expander for Softwareversion-->
<Expander Header="{x:Static language:Lang.ExpSoftwareVersion}" FontSize="11" HorizontalAlignment="Stretch" Margin="5,0,5,5">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<StackPanel Orientation="Vertical">
<TextBox x:Name="txtNCVersion" Text="{Binding NCVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgNCVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtHMIVersion" Text="{Binding HMIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHMIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtHRIVersion" Text="{Binding HRIVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgHRIVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
<TextBox x:Name="txtAHSVersion" Text="{Binding AHSVersion, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.Hint="{x:Static language:Lang.DgAHSVersion}" materialDesign:TextFieldAssist.HasClearButton="True" Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalAlignment="Center" Margin="5"/>
</StackPanel>
</Grid>
</Grid>
</Expander>
</StackPanel>
</materialDesign:Card>
<!--Database datagrid-->
<DataGrid x:Name="MachineDataGrid" Margin="5" AutoGenerateColumns="False" MaxHeight="700" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" ItemsSource="{Binding DataContext, Mode=TwoWay}" SelectedItem="{Binding Path=MachineSelectedItem, Mode=TwoWay}">
<ie:Interaction.Triggers>
<ie:EventTrigger EventName="SelectionChanged">
<ie:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding ElementName=MachineDataGrid, Path=SelectedItem}"/>
</ie:EventTrigger>
</ie:Interaction.Triggers>
<DataGrid.Columns>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgMachineID}" Binding="{Binding MachineID, Mode=TwoWay}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerId}" Binding="{Binding CustomerID}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCustomerName}" Binding="{Binding CustomerName}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCity}" Binding="{Binding City}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgCountry}" Binding="{Binding Country}"/>
<materialDesign:DataGridTextColumn Header="Part Name" Binding="{Binding PartName}"/>
<materialDesign:DataGridTextColumn Header="Part Number" Binding="{Binding PartNumber}"/>
<materialDesign:DataGridTextColumn Header="Project" Binding="{Binding Project}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC1}" Binding="{Binding SpindleC1}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgSpindleC2}" Binding="{Binding SpindleC2}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHoningHead}" Binding="{Binding HoningHead}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgNCVersion}" Binding="{Binding NCVersion}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHMIVersion}" Binding="{Binding HMIVersion}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgHRIVersion}" Binding="{Binding HRIVersion}"/>
<materialDesign:DataGridTextColumn Header="{x:Static language:Lang.DgAHSVersion}" Binding="{Binding AHSVersion}"/>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</Grid>
ViewModel:
public class MachineViewModel : ViewModelBase
{
#region public statments Textbox text
//Public statments to get textbox text
public string MachineID { get; set; }
public string CustomerID { get; set; }
public string CustomerName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PartName { get; set; }
public string PartNumber { get; set; }
public string Project { get; set; }
public string SpindleC1 { get; set; }
public string SpindleC2 { get; set; }
public string HoningHead { get; set; }
public string NCVersion { get; set; }
public string HMIVersion { get; set; }
public string HRIVersion { get; set; }
public string AHSVersion { get; set; }
#endregion
//DialogService
private IDialogService _dialogService;
//Operation button for save, update, delete, selection changed and print
public ICommand SaveCommand { get; private set; }
public ICommand UpdateCommand { get; private set; }
public ICommand DeleteCommand { get; private set; }
public ICommand ClearCommand { get; private set; }
public ICommand SelectionChangedCommand { get; set; }
//observable collection for machine model
public ObservableCollection<Machine> DataContext { get; set; }
private Machine machineSelectedItem;
public Machine MachineSelectedItem
{
get { return machineSelectedItem; }
set { machineSelectedItem = value; }
}
public object MachineDataGrid { get; set; }
public List<MachineClient> cmbclientDetails;
//PRWContext for general use
private PRWContext context = new PRWContext();
public MachineViewModel()
{
//Commands for save, update, delete and print
SaveCommand = new RelayCommand(() => ExecuteSaveCommand());
UpdateCommand = new RelayCommand(() => ExecuteUpdateCommand());
DeleteCommand = new RelayCommand(() => ExecuteDeleteCommand());
ClearCommand = new RelayCommand(() => ExecuteClearCommand());
SelectionChangedCommand = new RelayCommand(() => ExecuteSelectionChangedCommand());
//Load the data from PRW Database to datagrid
LoadData();
//Normelly done with dependency injection
_dialogService = new DialogService();
}
//execute save
private void ExecuteSaveCommand()
{
Machine machine = new Machine
{
//Machine data
MachineID = MachineID,
CustomerID = CustomerID,
CustomerName = CustomerName,
City = City,
Country = Country,
//Part data
PartName = PartName,
PartNumber = PartNumber,
Project = Project,
//Serial data
SpindleC1 = SpindleC1,
SpindleC2 = SpindleC2,
HoningHead = HoningHead,
//Softwareversion data
NCVersion = NCVersion,
HMIVersion = HMIVersion,
HRIVersion = HRIVersion,
AHSVersion = AHSVersion
};
context.Machines.Add(machine);
context.SaveChanges();
ClearContent();
}
//execute update
private void ExecuteUpdateCommand()
{
Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);
machine.CustomerID = CustomerID;
machine.CustomerName = CustomerName;
machine.City = City;
machine.Country = Country;
machine.PartName = PartName;
machine.PartNumber = PartNumber;
machine.Project = Project;
machine.SpindleC1 = SpindleC1;
machine.SpindleC2 = SpindleC2;
machine.HoningHead = HoningHead;
machine.NCVersion = NCVersion;
machine.HMIVersion = HMIVersion;
machine.HRIVersion = HRIVersion;
machine.AHSVersion = AHSVersion;
context.Machines.AddOrUpdate(machine);
context.SaveChanges();
ClearContent();
}
//execute delete
private void ExecuteDeleteCommand()
{
if (machineSelectedItem != null)
{
var dialog = new YesNoDialogViewModel("Question", "Your are Sure to Delete the Record?");
var result = _dialogService.OpenDialog(dialog);
if (result == DialogResults.Yes)
{
Machine machine = context.Machines.FirstOrDefault(w => w.MachineID == MachineID);
context.Machines.Remove(machine);
context.SaveChanges();
ClearContent();
}
}
else
{
var dialog = new AlertDialogViewModel("Attention", "Please select a Record!");
var result = _dialogService.OpenDialog(dialog);
Console.WriteLine(result);
}
}
//execute clear
private void ExecuteClearCommand()
{
ClearContent();
}
// Execute selection changed
private void ExecuteSelectionChangedCommand()
{
if(machineSelectedItem != null)
{
MachineID = machineSelectedItem.MachineID?.ToString() ?? "";
CustomerID = machineSelectedItem.CustomerID?.ToString() ?? "";
CustomerName = machineSelectedItem.CustomerName?.ToString() ?? "";
City = machineSelectedItem.City?.ToString() ?? "";
Country = machineSelectedItem.Country?.ToString() ?? "";
PartName = machineSelectedItem.PartName?.ToString() ?? "";
PartNumber = machineSelectedItem.PartNumber?.ToString() ?? "";
Project = machineSelectedItem.Project?.ToString() ?? "";
SpindleC1 = machineSelectedItem.SpindleC1?.ToString() ?? "";
SpindleC2 = machineSelectedItem.SpindleC2?.ToString() ?? "";
HoningHead = machineSelectedItem.HoningHead?.ToString() ?? "";
NCVersion = machineSelectedItem.NCVersion?.ToString() ?? "";
HMIVersion = machineSelectedItem.HMIVersion?.ToString() ?? "";
HRIVersion = machineSelectedItem.HRIVersion?.ToString() ?? "";
AHSVersion = machineSelectedItem.AHSVersion?.ToString() ?? "";
}
else
{
machineSelectedItem = null;
}
}
//Load data from database to grid
private void LoadData()
{
context.Machines.Load();
this.DataContext = context.Machines.Local;
}
//Clear textboxes
private void ClearContent()
{
MachineID = string.Empty;
CustomerID = string.Empty;
CustomerName = string.Empty;
City = string.Empty;
PartName = string.Empty;
PartNumber = string.Empty;
Project = string.Empty;
Country = string.Empty;
SpindleC1 = string.Empty;
SpindleC2 = string.Empty;
HoningHead = string.Empty;
NCVersion = string.Empty;
HMIVersion = string.Empty;
HRIVersion = string.Empty;
AHSVersion = string.Empty;
}
}
I have a counter which increments depending on a foreach Loop from:
public partial class UserControlCounter : UserControl, INotifyPropertyChanged
{
private int _scanStatusCounter;
public int ScanStatusCounter
{
get { return _scanStatusCounter; }
set { _scanStatusCounter = value; NotifyPropertyChanged(); }
}
public UserControlCounter()
{
InitializeComponent();
DataContext = this;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await Task.Run(getAll);
scanStatus.Text = "Persons " + ScanStatusCounter.ToString();
}
private async void getAll()
{
//grab data and iterate it
string[] string_array = new string[] { "a", "b", "c", "d", "e" }; // type = System.String[]
foreach (var i in string_array)
{
ScanStatusCounter++;
await Task.Delay(100);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
and the Xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0" Name="myListBox" Height="40" ></ListBox>
<TextBlock Grid.Row="0" Grid.Column="1" Name="scanStatus" Height="40" Text="{Binding Path=ScanStatusCounter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
<Button Grid.Row="0" Grid.Column="2" Click="Button_Click" Height="40">Click Me</Button>
</Grid>
That works fine and increments "live", but my problem is that I need to get that now running inside a more complex Data Template.
I've tried to inject the Counter onClick with:
private async void Button_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
var contentPresenter = (btn.TemplatedParent as ContentPresenter);
var ppStatusCounter = contentPresenter.ContentTemplate.FindName("scanStatus", contentPresenter) as TextBlock;
ppStatusCounter.Text = "Entrys found: " + ScanStatusCounter.ToString();
}
But then I get the Value only onClick not like a live incrementing Counter, that's my Data Template:
<UserControl.Resources>
<c1:NameList x:Key="NameListData"/>
<DataTemplate x:Key="NameItemTemplate">
<Grid Margin="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Domaine"/>
<TextBox Grid.Row="1" Grid.Column="0" x:Name="txtDomainName" Text="{Binding Path=DomaineName}" Margin="0,0,5,0"></TextBox>
<Button Grid.Row="1" Grid.Column="1" Width="100" Height="30" Margin="5,5,5,5" x:Name="btnNames" Click="Button_Click" Content="Start Scan" />
<Grid Grid.Column="2" Grid.Row="1" Height="20">
<ProgressBar x:Name="pbStatus" Height="20" Width="100" Minimum="0" Maximum="100" Visibility="Hidden"/>
<TextBlock x:Name="pbStatusText" HorizontalAlignment="Center" VerticalAlignment="Center" Text="Scanning" Visibility="Hidden"/>
</Grid>
<TextBlock Grid.Column="3" Grid.Row="1" Name="scanStatus" Text="{Binding Path=ScanStatusCounter, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid>
<StackPanel Orientation="Horizontal" VerticalAlignment="top">
<StackPanel Orientation="Horizontal" Margin="0,20,0,0">
<ListBox x:Name="lstDomainNames"
Margin="5,5,5,5"
ItemsSource="{Binding Source={StaticResource NameListData}}"
ItemTemplate="{StaticResource NameItemTemplate}"
IsSynchronizedWithCurrentItem="True"/>
</StackPanel>
</StackPanel>
</Grid>
that's my Data Source Class, not much there:
public partial class NameList : ObservableCollection<SetCredentials>
{
private static Logger logger = LogManager.GetCurrentClassLogger();
public NameList() : base()
{
using var forest = Forest.GetCurrentForest();
Forest currentForest = Forest.GetCurrentForest();
DomainCollection domains = currentForest.Domains;
foreach (Domain objDomain in domains)
{
Add(new SetCredentials(objDomain.ToString()));
}
}
}
public class SetCredentials
{
private string domainName;
public SetCredentials(string domain)
{
this.domainName = domain;
}
public string DomaineName
{
get { return domainName; }
set { domainName = value; }
}
}
Do I have to add a second Data Binding source to my ItemSource or do I need another approach for this, for example in my TextBox Binding?
I'm learning wpf through mvvm.
My application consist of below logic.
Form which has a button that will add a selected components horizontally from Itemcontrol like textbox, combobox and rich textbox and a button whenever the button is clicked.
When the add button is clicked the specified set of components will be added in the line information dynamically.
2) Data will be inserted into the table after pressing the add info button.
3) The issue is after clicking the add info button, the components in the itemscontrol should be readonly. This is the place I'm struggling as of now.
Model.cs:
public class textboxModel
{
public string Text { get; set; }
public string lblText { get; set; }
public string isactive { get; set; }
public bool txtboxreadonly { get; set; }
}
public class ButtonDataModel
{
public string Content { get; set; }
public ICommand Command { get; set; }
public string column { get; set; }
public string isactive { get; set; }
public bool buttreadonly { get; set; }
}
ViewModel.cs:
public class viewmodel : notifyproperties
{
public Relaycommand Status { get; set; }
public Relaycommand AddCommand { get; set; }
public labelconversionOnPauseButtonclick pauseclick = new labelconversionOnPauseButtonclick();
public auditinformation auditid = new auditinformation();
public ButtonDataModel bdm = new ButtonDataModel();
public auditinformation adt
{
get { return auditid; }
set
{
if (value != auditid)
{
auditid = value;
OnPropertyChanged("adt");
}
}
}
public labelconversionOnPauseButtonclick res
{
get { return pauseclick; }
set
{
if (value != pauseclick)
{
pauseclick = value;
OnPropertyChanged("res");
}
}
}
public viewmodel()
{
Status = new Relaycommand(pauseclick.Statusdata);
AddCommand = new Relaycommand(o => auditid.addcommand());
}
}
public class auditinformation : notifyproperties
{
public Relaycommand Command { get; set; }
private string _lines;
public string Lines
{
get { return this._lines; }
set
{
this._lines = value;
this.OnPropertyChanged("Lines");
}
}
private readonly ObservableCollection<ButtonDataModel> _MyDatabutton = new ObservableCollection<ButtonDataModel>();
public ObservableCollection<ButtonDataModel> MyData { get { return _MyDatabutton; } }
private readonly ObservableCollection<textboxModel> _MyDatatxtbox = new ObservableCollection<textboxModel>();
public ObservableCollection<textboxModel> MyDatatxtbox { get { return _MyDatatxtbox; } }
private readonly ObservableCollection<LabelDataModel> _MyDataLabel = new ObservableCollection<LabelDataModel>();
public ObservableCollection<LabelDataModel> MyDataLabel { get { return _MyDataLabel; } }
public void addcommand()
{
int num= 1;
for (int i = 0; i < num; i++)
{
MyDatatxtbox.Add(new textboxModel
{
isactive = "1",
});
MyData.Add(new ButtonDataModel
{
Command = new Relaycommand(o => search()),
Content = "Add info",
isactive = "1",
});
}
}
public void search( )
{
var asss = MyDatatxtbox.Where(a=> a.isactive == "1").Select(a => a.Text);
var itemstoremove = MyDatatxtbox.Where(i => i.isactive == "1").ToList();
foreach (var s in asss)
{
foreach (var a in itemstoremove)
{
if (a.isactive == "1")
{
MessageBox.Show(s);
buttreadonly = true;
}
}
}
// var itemstoremove = MyDatatxtbox.Where(i => i.isactive == "1").ToList();
foreach(var a in itemstoremove)
{
a.isactive = "0";
}
//foreach (var a in itemstoremove)
//{
// a.txtboxreadonly = true;
//}
// var itemstoremovebutton = MyData.Where(i => i.isactive == "1").ToList();
// foreach (var a in itemstoremovebutton)
// {
//// MyData.Remove(a);
// a.isactive = "0";
// }
}
}
window.xaml:
<GroupBox Header="Audit Information" Grid.Row="1">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="0" Text="Member ID"></TextBlock>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="1" Width="85" ></TextBox>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="2" Text="Claim Number"></TextBlock>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="3" Width="85" ></TextBox>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="4" Text="Date Audited"></TextBlock>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="5" Width="85" ></TextBox>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="6" Text="Query ID"></TextBlock>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="7" Width="85" ></TextBox>
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="8" Text="Audit ID"></TextBlock>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="9" Width="85" ></TextBox>
<Button HorizontalAlignment="Center" VerticalAlignment="Center" Width="85" Height="25" Command="{Binding AddCommand}" Content="Add" Grid.Column="10"></Button>
</Grid>
</GroupBox>
<GroupBox Grid.Row="2" Margin="0,0,0,0" Header="Line Information" >
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="3.2*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="1.8*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Height="22" Grid.Column="0">
<Label HorizontalAlignment="Center" Content="DOS" />
</StackPanel>
<ItemsControl Grid.Column="0" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,50">
<TextBox IsReadOnly="{Binding txtboxreadonly}" Text="{Binding Text, Mode=TwoWay}" Height="25" Width="85" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Height="22" Grid.Column="1">
<Label HorizontalAlignment="Center" Content="CPT" />
</StackPanel>
<ItemsControl Grid.Column="1" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,50">
<TextBox IsReadOnly="{Binding txtboxreadonly}" Margin="0,0,30,0" Text="{Binding Text, Mode=TwoWay}" Height="25" Width="85" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Height="22" Grid.Column="2">
<Label HorizontalAlignment="Right" Content="Open-close Modifier" Margin="0,0,-17,0" Width="121" />
</StackPanel>
<ItemsControl Grid.Column="2" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,50">
<TextBox IsReadOnly="{Binding txtboxreadonly}" Margin="0,0,30,0" Text="{Binding Text, Mode=TwoWay}" Height="25" Width="85" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Height="22" Grid.Column="3">
<Label HorizontalAlignment="Center" Content="Comments" />
</StackPanel>
<ItemsControl Grid.Column="3" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,10">
<RichTextBox IsReadOnly="{Binding txtboxreadonly}" Margin="0,0,0,0" Height="65" Width="425" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Height="22" Grid.Column="4">
<Label HorizontalAlignment="Center" Content="Line Status" />
</StackPanel>
<ItemsControl Grid.Column="4" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="10,0,0,50">
<ComboBox IsEnabled= "{Binding txtboxreadonly}" Margin="0,0,0,0" Height="25" Width="95" >
<ComboBoxItem Content="Coffie"></ComboBoxItem>
<ComboBoxItem Content="Tea"></ComboBoxItem>
</ComboBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<StackPanel Height="22" Grid.Column="5">
<Label HorizontalAlignment="Center" Content="Additional Comments" />
</StackPanel>
<ItemsControl Grid.Column="5" Grid.Row="1" ItemsSource="{Binding adt.MyDatatxtbox}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,10">
<RichTextBox IsReadOnly="{Binding txtboxreadonly}" Margin="0,0,0,0" Height="65" Width="425" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl Grid.Column="6" Grid.Row="1" ItemsSource="{Binding adt.MyData}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,50">
<Button Margin="0,0,0,0" Height="25" Width="55" Content="{Binding Content}" Command="{Binding Command}" >
</Button>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</ScrollViewer>
</GroupBox>
</Grid>
</Grid>
</TabItem>
</TabControl>
So the question is how to disable/readonly the Line Information ,textbox and cpt on add info button click.
Dirty way would be adding a "global" bool property in your ViewModel and binding it to your Controls IsEnabled/ReadOnly Properties.
Is there any way to get the index of the data which is binded to the ItemsControl, when a button is clicked?
<ItemsControl x:Name="ic_schranke" DataContext="{Binding Schranke}" >
<ItemsControl.ItemTemplate>
<DataTemplate >
<Button Height="80" x:Name="btn_open" Click="btn_open_Click" HorizontalAlignment="Stretch" Style="{StaticResource TransparentStyle}">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="30*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Rectangle x:Name="rect" Grid.ColumnSpan="3" Grid.Row="1" Opacity="0.65" Grid.Column="0" Fill="#FFCEEAFF"/>
<Border CornerRadius="25" Height="50" Width="50" HorizontalAlignment="Center" Grid.Column="0" Grid.Row="1">
<Border.Background>
<ImageBrush ImageSource="/Assets/schranken.jpg" />
</Border.Background>
</Border>
<TextBlock Name="schranken_name" Grid.Column="1" Grid.Row="1" Text="{Binding name}" VerticalAlignment="Center" HorizontalAlignment="Center" FontWeight="ExtraLight" Foreground="Black" />
</Grid>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Here is the sample data which is binded to the IC:
List<Schranke> elements;
public UserPage()
{
this.InitializeComponent();
elements = new List<Schranke>();
for (var i = 1; i < 15; i++)
elements.Add(new Schranke() { name = $"Schranke NR:{i}" });
this.ic_schranke.ItemsSource = elements;
}
And here is the code in the button click event:
private async void btn_open_Click(object sender, RoutedEventArgs e)
{
Grid grid = (sender as Button).Content as Grid;
//Debug.WriteLine($"content {tb.Text} clicked");
var tmp_background = grid.Background;
grid.Background = new SolidColorBrush(new Windows.UI.Color() { A = 255, R = 78, G = 170, B = 44 });
VibrationDevice testVibrationDevice = VibrationDevice.GetDefault();
testVibrationDevice.Vibrate(System.TimeSpan.FromMilliseconds(150));
await Task.Delay(3000);
grid.Background = tmp_background;
}
Maybe something along the lines of this:
the presenter - put this in the data context
public class SchrankePresenter : INotifyPropertyChanged
{
private List<Schranke> _elements;
public List<Schranke> Elements
{
get { return _elements; }
set
{
_elements = value;
OnPropertyChanged("Elements");
}
}
public ICommand ClickCommand { get; set; }
private void OnPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public event PropertyChangedEventHandler PropertyChanged;
public SchrankePresenter()
{
var elements = new List<Schranke>();
for (var i = 1; i < 15; i++)
elements.Add(new Schranke() { Name = $"Schranke NR:{i}" });
Elements = elements;
ClickCommand = new DelegateCommand(ClickAction);
}
public void ClickAction(Schranke item)
{
VibrationDevice.GetDefault().Vibrate(TimeSpan.FromMilliseconds(150));
}
}
public class Schranke
{
public string Name { get; set; }
}
the template:
<ListView ItemsSource="{Binding Elements}">
<ListView.ItemTemplate>
<DataTemplate>
<Button Height="80"
HorizontalAlignment="Stretch"
Command="{Binding ClickCommand}"
Style="{StaticResource TransparentStyle}">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="30*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Rectangle x:Name="rect"
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="3"
Fill="#FFCEEAFF"
Opacity="0.65" />
<Border Grid.Row="1"
Grid.Column="0"
Width="50"
Height="50"
HorizontalAlignment="Center"
CornerRadius="25">
<Border.Background>
<ImageBrush ImageSource="/Assets/schranken.jpg" />
</Border.Background>
</Border>
<TextBlock Name="schranken_name"
Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontWeight="ExtraLight"
Foreground="Black"
Text="{Binding Name}" />
</Grid>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
you can do the background animation using a storyboard/visualstate
EDIT : regarding the DelegateCommand, it's a simple implementation I use for my WPF apps -
internal class DelegateCommand<T> : ICommand
{
private Action<T> _clickAction;
public DelegateCommand(Action<T> clickAction)
{
_clickAction = clickAction;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_clickAction((T)parameter);
}
}
So I'm having what should be a simple XAML Data Binding error. I've got the below XAML with two classes (so far) that they used for DataBinding, a Row, which contains an ObservableCollection rows. The nodes have a bunch of extra associated information and I'm trying to show these nodes in a grid-like fashion (it's going to be used for a path-finding algorithm.)
The problem is that the "Here" TextBlock doesn't show up. But I know that the Nodes are getting bound properly because their values show up in the Debugging StackPanel.
<Window.Resources>
<local:Row x:Key="TestRow">
<local:Node x="0" y="0" Cost="20" />
<local:Node x="0" y="1" Cost="20" />
<local:Node x="0" y="2" Cost="20" />
</local:Row>
</Window.Resources>
<Grid Name="MainGrid" Margin="10,10,10,10" >
<Grid.RowDefinitions>
<RowDefinition Height="150" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Margin="0,25,0,0"
DataContext="{Binding ElementName=AStarListView,
Path=SelectedItem}"
x:Name="Debugging" Orientation="Vertical" >
<TextBlock Text="{Binding x}" />
<TextBlock Text="{Binding y}" />
<TextBlock Text="{Binding Cost}" />
</StackPanel>
<ListView Grid.RowSpan="2" Margin="2,2,2,2" Grid.Column="1"
x:Name="AStarListView"
ItemsSource="{StaticResource TestRow}" >
<ListView.ItemTemplate>
<DataTemplate DataType="local:Row">
<ListView ItemsSource="{Binding nodes}" Width="48" Height="48" >
<ListView.ItemTemplate>
<DataTemplate DataType="local:Node">
<TextBlock Text="Here" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here's the (stripped) Node class.
public class Node : INotifyPropertyChanged
{
public Tuple<int, int> coordinates { get; set; }
public int x
{
get
{
if (this.coordinates == null)
return -1;
return this.coordinates.Item1;
}
set
{
if (this.coordinates != null)
this.coordinates = new Tuple<int, int>(value, y);
else
this.coordinates = new Tuple<int, int>(value, -1);
OnPropertyChanged("x");
}
}
public int y
{
get
{
if (this.coordinates == null)
return -1;
return this.coordinates.Item2;
}
set
{
if (this.coordinates != null)
this.coordinates = new Tuple<int, int>(x, value);
else
this.coordinates = new Tuple<int, int>(-1, value);
OnPropertyChanged("y");
}
}
private Node _parent;
private int _Cost;
public int Cost
{
get
{
return _Cost;
}
set
{
_Cost = value;
OnPropertyChanged("Cost");
}
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChangedEventArgs args =
new PropertyChangedEventArgs(propertyName);
this.PropertyChanged(this, args);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Here's the Row class:
public class Row : ObservableCollection<Node>
{
public ObservableCollection<Node> nodes { get; set; }
public Row()
{
this.nodes = new ObservableCollection<Node>();
}
}
Here's the corrected XAML, the class definitions are correct in the question, need to replace "AStarListView" with this XAML.
<ListView Grid.RowSpan="2" Margin="2,2,2,2" Grid.Column="1" x:Name="AStarListView"
ItemsSource="{StaticResource TestRow}" >
<ListView.ItemTemplate>
<DataTemplate DataType="local:Node">
<Grid Background="#dddddd" >
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding x}"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding y}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Cost}"/>
<Grid.RowDefinitions>
<RowDefinition Height="24"/>
<RowDefinition Height="24"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="24"/>
<ColumnDefinition Width="24"/>
</Grid.ColumnDefinitions>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
My problem was that I had the ListViews too deeply nested. The inner ListView was binding to the "nodes" property of a Node, which didn't exist.