I am creating a Data Entry Form having a ComboBox & Few TextBoxes in First Row. I want a new Row with same Elements to be Generated on Pressing Enter Key from Last TextBox in First Row.
How do i achieve it? Is there any Data Template or Item Template or anything as such that can work for this Data Entry Form.
I also read about Observable Collection Class & IEnumerable, can this help me achieving? How?
I am Newbie to WPF & MVVM, have done a lot of research but couldn't find the exact solution.
I have already done this,
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="420">
<Grid Name="_mainGrid" HorizontalAlignment="Left">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="227"/>
<ColumnDefinition Width="77" />
<ColumnDefinition Width="77" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="27"/>
</Grid.RowDefinitions>
</Grid>
</Window>
Also my .CS Code is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using System.Reflection;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int rowIndex, Dr = 0, Cr = 0;
TextBox PTextBox, DrAmtTextBox, CrAmtTextBox;
ComboBox Combobox;
List<TextBox> txtboxParticulars = new List<TextBox>();
List<TextBox> txtboxDrAmount = new List<TextBox>();
List<TextBox> txtboxCrAmount = new List<TextBox>();
List<ComboBox> cmbboxDrCr = new List<ComboBox>();
public MainWindow()
{
InitializeComponent();
CreateRow();
}
public void CreateRow()
{
RowDefinition newRow = new RowDefinition();
newRow.Height = new GridLength(30, GridUnitType.Pixel);
_mainGrid.RowDefinitions.Insert(_mainGrid.RowDefinitions.Count - 1, newRow);
rowIndex = _mainGrid.RowDefinitions.Count - 2;
AddComboBox();
AddPTextBox();
AddDrCrTextBox();
}
public void AddComboBox()
{
Combobox = new ComboBox();
Combobox.Items.Add("Dr.");
Combobox.Items.Add("Cr.");
Combobox.SelectedItem = "Dr.";
Combobox.Height = 25;
Combobox.Name = "DrCr" + rowIndex.ToString();
Combobox.SelectionChanged += new SelectionChangedEventHandler(Combobox_SelectionChanged);
Combobox.KeyUp += new KeyEventHandler(Combobox_KeyUp);
Grid.SetRow(Combobox, rowIndex);
Grid.SetColumn(Combobox, 0);
_mainGrid.Children.Add(Combobox);
cmbboxDrCr.Add(new ComboBox { Text = Combobox.Name });
cmbboxDrCr[rowIndex].Text = "Dr.";
Combobox.Focus();
}
void Combobox_KeyUp(object sender, KeyEventArgs e)
{
if (Combobox.SelectedItem.ToString() == "Dr.")
{
cmbboxDrCr[rowIndex].Text = "Dr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
}
else
{
cmbboxDrCr[rowIndex].Text = "Cr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
}
}
void Combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Combobox.SelectedItem.ToString() == "Dr.")
{
cmbboxDrCr[rowIndex].Text = "Dr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
PTextBox.Focus();
}
else
{
cmbboxDrCr[rowIndex].Text = "Cr.";
DrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.Visibility = System.Windows.Visibility.Visible;
PTextBox.Focus();
}
}
public void AddPTextBox()
{
PTextBox = new TextBox();
PTextBox.Name = "Particulars" + rowIndex.ToString();
PTextBox.Height = 25;
PTextBox.Width = 225;
Grid.SetRow(PTextBox, rowIndex);
Grid.SetColumn(PTextBox, 1);
_mainGrid.Children.Add(PTextBox);
txtboxParticulars.Add(new TextBox { Text = PTextBox.Name });
}
public void AddDrCrTextBox()
{
DrAmtTextBox = new TextBox();
DrAmtTextBox.Name = "Dr" + rowIndex.ToString();
DrAmtTextBox.Height = 25;
DrAmtTextBox.Width = 75;
DrAmtTextBox.KeyDown += new KeyEventHandler(DrCrAmtTextBox_KeyDown);
Grid.SetRow(DrAmtTextBox, rowIndex);
Grid.SetColumn(DrAmtTextBox, 2);
_mainGrid.Children.Add(DrAmtTextBox);
txtboxDrAmount.Add(new TextBox { Text = DrAmtTextBox.Name });
CrAmtTextBox = new TextBox();
CrAmtTextBox.Name = "Cr" + rowIndex.ToString();
CrAmtTextBox.Height = 25;
CrAmtTextBox.Width = 75;
CrAmtTextBox.Visibility = System.Windows.Visibility.Hidden;
CrAmtTextBox.KeyDown += new KeyEventHandler(DrCrAmtTextBox_KeyDown);
Grid.SetRow(CrAmtTextBox, rowIndex);
Grid.SetColumn(CrAmtTextBox, 3);
_mainGrid.Children.Add(CrAmtTextBox);
txtboxCrAmount.Add(new TextBox { Text = DrAmtTextBox.Name });
}
void DrCrAmtTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
AddDataToList();
CountDrCr();
CreateRow();
}
}
void CountDrCr()
{
for (int i = 0; i <= rowIndex; i++)
{
if (cmbboxDrCr[i].Text == "Dr.")
{
Dr++;
}
else
{
Cr++;
}
}
}
void AddDataToList()
{
cmbboxDrCr[rowIndex].Text = Combobox.Text;
txtboxParticulars[rowIndex].Text = PTextBox.Text;
txtboxDrAmount[rowIndex].Text = CrAmtTextBox.Text;
txtboxCrAmount[rowIndex].Text = DrAmtTextBox.Text;
MessageBox.Show(cmbboxDrCr[rowIndex].Text +" "+ txtboxParticulars[rowIndex].Text + " " + txtboxDrAmount[rowIndex].Text + " " + txtboxCrAmount[rowIndex].Text);
}
}
}
I know this is not the Right way, so please help me with WPF MVVM method of doing this!!!
After going through the Answers here i have done the Following
Created a DataType
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataTemplate
{
class YourDataType
{
public string DrCr { get; set; }
public string Particulars { get; set; }
public float Amount { get; set; }
public string Narration { get; set; }
}
}
MainWindow.Xaml File
<Window x:Class="DataTemplate.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataTemplate"
Title="MainWindow" Height="350" Width="750">
<Grid>
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type local:YourDataType}">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Horizontal">
<ComboBox SelectedIndex="0">
<ComboBoxItem Content="Dr."/>
<ComboBoxItem Content="Cr."/>
</ComboBox>
<TextBox Width="350"/>
<TextBox Width="150"/>
</StackPanel>
<Label Content="Narration"/>
<TextBox Width="450"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
MainWindow.CS File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
namespace DataTemplate
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<YourDataType> YourCollection;
public MainWindow()
{
InitializeComponent();
YourCollection.Add(new YourDataType());
}
}
}
While it may seem natural for a non WPF developer to build their UI in code, that is generally not how it is done in WPF. Learn to do it in XAML and you will save yourself many headaches.
First create a data type, let's call it YourDataType for example, that contains all of the required properties for each 'row'. Then declare an ObservableCollection<YourDataType> property to data bind to a collection control, let's call it YourCollection. Finally, declare a DataTemplate that defines what each row should look like:
<ListBox ItemsSource="{Binding YourCollection}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type YourPrefix:YourDataType}">
<!-- Define your 'row' controls here -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now to add a new empty row, all you need to do is to add a new item to your data bound collection:
YourCollection.Add(new YourDataType());
For further information, please refer to the Data Binding Overview page on MSDN.
You can create a WPF User Control with the complete structure inside (the comboBoxand and the textboxes), you can create a single list of this usercontrol
for example you can create a FormRow.xaml user control similar to this one....
<UserControl x:Class="WPFTEST.FormRow"
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"
mc:Ignorable="d"
Width="500" Height="26">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<ComboBox Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="1" Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="2" Margin="0"/>
<TextBox TextWrapping="Wrap" Text="TextBox" Grid.Column="3" Margin="0"/>
</Grid>
</UserControl>
And you can add events and control the model object information from the codebehind.....
in the main window you can have a listView or a Stack full of instances of this single control each instance is a view to a model object and preserves the acess hierarchy....
Related
How can i make a richtextbox that supports color and saves the richtextbox content in a rtf file with wpf and c#? I want that the user can select a word in a richtextbox and give it a special font color. And that the user can save the richtextbox with the special color into a .rtf file and load it back into the richtextbox with the special color.
Here you have something to get you started:
Write a filename with path like "C:\test.rtf"
Click on "Open" even if the file is new.
Add some text below "Document"
Select a word and click on the ".. add color.. " button.
Save the file.
Restart the program and open the file. The text should appear in the Document field.
XAML:
<Window x:Class="WpfApp11.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp11"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="File path: "/>
<TextBox x:Name="filePathBox" Width="300" Margin="5,0,0,0"/>
</StackPanel>
<Button x:Name="open" Click="open_Click" Content="Open" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<TextBlock Text="Document" Margin="0,5,0,0"/>
<RichTextBox x:Name="richTextBox" Margin="0,5,0,0"/>
<Button x:Name="addColor" Click="addColor_Click" Content="Select and press this button to add color to text" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<Button x:Name="save" Click="save_Click" Content="Save" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
<TextBlock Text="Status"/>
<TextBlock x:Name="statusBox" Width="300" Margin="0,5,0,0" HorizontalAlignment="Left"/>
</StackPanel>
</Grid>
</Window>
Code behind (xaml.cs)
using System;
using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace WpfApp11
{
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = this;
InitializeComponent();
}
private void addColor_Click(object sender, RoutedEventArgs e)
{
richTextBox.Selection.ApplyPropertyValue(ForegroundProperty, new SolidColorBrush(Colors.Red));
}
private void open_Click(object sender, RoutedEventArgs e)
{
try
{
TextRange range;
FileStream fStream;
string filename = filePathBox.Text;
if (File.Exists(filename))
{
range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
using (fStream = new FileStream(filename, FileMode.OpenOrCreate))
{
range.Load(fStream, DataFormats.Rtf);
fStream.Close();
}
statusBox.Text = "File opened.";
}
else
{
statusBox.Text = "File new.";
}
}
catch (Exception excep)
{
statusBox.Text = excep.Message;
}
}
private void save_Click(object sender, RoutedEventArgs e)
{
try
{
TextRange range;
FileStream fStream;
range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
string filename = filePathBox.Text;
using (fStream = new FileStream(filename, FileMode.Create))
{
range.Save(fStream, DataFormats.Rtf);
fStream.Close();
}
statusBox.Text = "File saved.";
}
catch (Exception excep)
{
statusBox.Text = excep.Message;
}
}
}
}
I have a textbox ACLBox that I want to display a string upon initialization of the user interface. Upon initializing, the string flashes for a second then disappears. Why?
Here's the xaml code for the textbox:
<Window x:Class="Funnel.ACL"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Funnel"
mc:Ignorable="d"
Title="ACL Configuration" Height="300" Width="560" WindowStartupLocation="CenterScreen"
Closing="exitACL"
Background="LightGray" Name="ACLConfiguration">
<Grid>
<DockPanel>
<Grid x:Name="FunnelGrid" DockPanel.Dock="Top" ShowGridLines="False">
<!--Defining Grid-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="30"/>
<ColumnDefinition Width="70"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label x:Name="Config"
Content="ACL CONFIGURATION"
Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="9"
HorizontalAlignment="Center"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16">
</Label>
<CheckBox x:Name="aclCheckbox"
FlowDirection="RightToLeft"
Content="ACL ON"
Foreground="Blue"
FontWeight="Heavy"
FontSize="16"
Grid.Row="1"
Grid.Column="0"
Grid.RowSpan="1"
Grid.ColumnSpan="5"
HorizontalAlignment="Center"
Checked="ACL_Check"
Unchecked="ACL_Unchecked"
/>
<Label x:Name="AddIPAddress" Content="Add IP Address" Grid.Row="2" Grid.Column="0" Width="90" Height="30"></Label>
<TextBox x:Name="AddIPTextBox1" Grid.Row="2" Grid.Column="1" Width="35" Height="20" TextChanged="AddIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox2" Grid.Row="2" Grid.Column="2" Width="35" Height="20" TextChanged="AddIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox3" Grid.Row="2" Grid.Column="3" Width="35" Height="20" TextChanged="AddIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="AddIPTextBox4" Grid.Row="2" Grid.Column="4" Width="35" Height="20" TextChanged="AddIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="AddErrorBox" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding AddErrorText}"/>
<Button x:Name="AddButton" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="addClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">ADD</Button>
<Label x:Name="DelIPAddress" Content="Remove IP Address" Grid.Row="4" Grid.Column="0" Width="120" Height="30"></Label>
<TextBox x:Name="DeleteIPTextBox1" Grid.Row="4" Grid.Column="1" Width="35" Height="20" TextChanged="DeleteIPTextBox1_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox2" Grid.Row="4" Grid.Column="2" Width="35" Height="20" TextChanged="DeleteIPTextBox2_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox3" Grid.Row="4" Grid.Column="3" Width="35" Height="20" TextChanged="DeleteIPTextBox3_TextChanged"></TextBox>
<TextBox x:Name="DeleteIPTextBox4" Grid.Row="4" Grid.Column="4" Width="35" Height="20" TextChanged="DeleteIPTextBox4_TextChanged"></TextBox>
<TextBox x:Name="DelErrorBox" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalAlignment="Right" BorderThickness="0" Background="LightGray" FontSize="10" Text="{Binding DelErrorText}"/>
<Button x:Name="DeleteButton" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="50" Click="deleteClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">DELETE</Button>
<Button x:Name="DeleteAllButton" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="4" HorizontalAlignment="Center" Height="25" Width="80" Click="deleteAllClick" FontSize="12" FontWeight="ExtraBold" Background="LightSteelBlue" VerticalAlignment="Top">REMOVE ALL</Button>
<Label x:Name="ACLBoxLabel" Content="Access Control List" Foreground="Blue" Grid.Row="1" Grid.Column="6" Grid.ColumnSpan="3" HorizontalAlignment="Center"></Label>
<TextBox x:Name="ACLBox"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
Grid.Row="2"
Grid.Column="6"
Grid.RowSpan="4"
Grid.ColumnSpan="4"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="220"
Height="150"
FontSize="14"
IsReadOnly="True"
Text="{Binding ACLBoxText}"
TextWrapping="Wrap"
TextAlignment="Center" />
</Grid>
</DockPanel>
</Grid>
Here's the C# code for the string:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Funnel
{
/// <summary>
/// Interaction logic for ACL.xaml
/// </summary>
public partial class ACL : Window
{
AclManager _manage = new AclManager();
FileController _controller = new FileController();
string addStr1;
string addStr2;
string addStr3;
string addStr4;
bool addError;
string delStr1;
string delStr2;
string delStr3;
string delStr4;
bool delError;
public string aclText;
public event PropertyChangedEventHandler PropertyChanged;
public ACL()
{
InitializeComponent();
if(FunnelGlobals.accessControlList)
{
aclCheckbox.IsChecked = true;
}
aclText = _manage.getAclList();
}
private void exitACL(object sender,System.ComponentModel.CancelEventArgs e)
{
_controller.writeAclFile();
}
private void ACL_Check(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = true;
aclText = _manage.getAclList();
}
private void ACL_Unchecked(object sender, RoutedEventArgs e)
{
FunnelGlobals.accessControlList = false;
aclText = _manage.getAclList();
}
private void AddIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox1.Text = AddIPTextBox1.Text;
addStr1 = AddIPTextBox1.Text;
if(!_manage.isDigit(addStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
addError = true;
}
else
{
addError = false;
}
ACLBox.Text = _manage.getAclList();
}
private void AddIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox2.Text = AddIPTextBox2.Text;
addStr2 = AddIPTextBox2.Text;
if (!_manage.isDigit(addStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox3.Text = AddIPTextBox3.Text;
addStr3 = AddIPTextBox3.Text;
if (!_manage.isDigit(addStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void AddIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
AddErrorBox.Text = "";
AddIPTextBox4.Text = AddIPTextBox4.Text;
addStr4 = AddIPTextBox4.Text;
if (!_manage.isDigit(addStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Character NOT Valid";
}
aclText = _manage.getAclList();
}
private void addClick(object sender, RoutedEventArgs e)
{
String addStr = addStr1 + "." + addStr2 + "." + addStr3 + "." + addStr4;
if(_manage.isLegit(addStr))
{
FunnelGlobals.aclIPs.Add(addStr);
}
if(addError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
AddErrorBox.Foreground = errBrush;
AddErrorBox.Text = "Fix Invalid Characters before Adding";
}
else
{
aclText = _manage.getAclList();
}
}
private void DeleteIPTextBox1_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox1.Text = DeleteIPTextBox1.Text;
delStr1 = DeleteIPTextBox1.Text;
if (!_manage.isDigit(delStr1))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox2_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox2.Text = DeleteIPTextBox2.Text;
delStr2 = DeleteIPTextBox2.Text;
if (!_manage.isDigit(delStr2))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox3_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox3.Text = DeleteIPTextBox3.Text;
delStr3 = DeleteIPTextBox3.Text;
if (!_manage.isDigit(delStr3))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void DeleteIPTextBox4_TextChanged(object sender, TextChangedEventArgs e)
{
DelErrorBox.Text = "";
DeleteIPTextBox4.Text = DeleteIPTextBox4.Text;
delStr4 = DeleteIPTextBox4.Text;
if (!_manage.isDigit(delStr4))
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Character NOT Valid";
delError = true;
}
else
{
delError = false;
}
}
private void deleteClick(object sender, RoutedEventArgs e)
{
String delStr = delStr1 + "." + delStr2 + "." + delStr3 + "." + delStr4;
FunnelGlobals.aclIPs.Remove(delStr);
if (delError)
{
Color foreColor = (Color)new ColorConverter().ConvertFrom("red");
Brush errBrush = new SolidColorBrush(foreColor);
DelErrorBox.Foreground = errBrush;
DelErrorBox.Text = "Fix Invalid Characters before Removing";
}
else
{
aclText = _manage.getAclList();
}
}
private void deleteAllClick(object sender, RoutedEventArgs e)
{
FunnelGlobals.aclIPs.Clear();
aclText = _manage.getAclList();
}
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = _manage.getAclList();
}
public string ACLBoxText
{
get { return aclText; }
set { aclText = value; OnNotifyPropertyChanged("ACLBoxText"); }
}
private void OnNotifyPropertyChanged(string v)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(v));
throw new NotImplementedException();
}
}
}
Upon initializing, the string flashes for a second then disappears. Why?
Probably because you are "overwriting" the value of the ACLBoxText source property, which is initially displayed in the TextBlock, when you set the Text property of the TextBlock in your Loaded event handler.
If the TextBlock is empty once the UI has been loaded you should make sure that the _manage.getAclList() method returns the string that you expect it to return. You could temporarily try to assign the Text property to a "static" value:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBox.Text = "TEXT";
}
But I agree that it doesn't make much sense to first bind the Text property of the TextBlock to a source property in the XAML markup and then handle the Loaded event of the same TextBlock and set its Text property to a new value in this event handler. But I guess you have your reasons...
Note that binding that you define in the XAML markup will get reset when you programmatically set the Text property in your Loaded handler though.
So you should either don't bind the Text property in the XAML markup, or don't handle the Loaded event and set the Text property programmatically. It's one or the other but not both.
I figured out the problem. This is my first C# project and first time ever using Xaml (wpf) so I misunderstood binding. I bound the text like I did in the primary gui. The text is never getting triggered within this gui so I could only see the text flash because of loaded but then the text binding reset the textbox to nothing. When I changed my text to not be bound then everything works as I wanted. Lesson learned. Binding is only needed when accessing a textbox from within .cs files. It is not needed within xaml.cs. Since my text would only ever be triggered by xaml.cs just setting text the usual way(ie textbox.text = "whatever") does what I need. Thank you everyone for your help. I understand binding much, much better now. Java does things differently. :)
As Ed Plunkett has already mentioned, you should use your ACLBoxText backing variable instead of resetting the control value.
Something like this will work:
private void ACLBox_Loaded(object sender, RoutedEventArgs e)
{
ACLBoxText = _manage.getAclList();
}
Unfortunately, the view doesn't know about changes to backing properties unless you tell it that something changed. You need to implement INotifyPropertyChanged:
private string _aclBoxText;
public string ACLBoxText {
get { return _aclBoxText; }
set {
_aclBoxText = value;
OnNotifyPropertyChanged("ACLBoxText");
}
}
protected void OnNotifyPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
File Name SampleProject
My xaml file Mainwindow.xaml----------
<Window x:Class="SampleProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking" Closing="Window_Closing"
Title="MainWindow" Height="800" Width="800" WindowState="Maximized">
<Grid>
<dxdo:DockLayoutManager x:Name="docklayoutmanager1" dxdo:RestoreLayoutOptions.RemoveOldPanels="False" dxdo:RestoreLayoutOptions.RemoveOldLayoutControlItems="False" Margin="0,50,0,0">
</dxdo:DockLayoutManager>
<Button Width="100" VerticalAlignment="Top" HorizontalAlignment="Center" Height="30" x:Name="ClickMe" Content="Click Me" Click="ClickMe_Click" Margin="323,10,369,729" />
</Grid>
</Window>
`
My xaml.cs file MainWindow.xaml.cs-------------------
using DevExpress.Xpf.Docking;
using DevExpress.Xpf.Layout.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SampleProject
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
if(File.Exists("test.xml"))
{
docklayoutmanager1.RestoreLayoutFromXml("test.xml");
}
}
private void ClickMe_Click(object sender, RoutedEventArgs e)
{
var panel = docklayoutmanager1.DockController.AddPanel(DockType.None);
panel.Caption = "Test Panel";
panel.Name = "myPanel";
panel.Content = "I want to serialize this code using guid Please provide example for creating such binding.";
FloatGroup floatgroup = new FloatGroup();
floatgroup.Name = "myFloatGroup";
floatgroup.FloatSize = new Size(500,500);
floatgroup.FloatLocation = new Point(300, 300);
floatgroup.Add(panel);
docklayoutmanager1.FloatGroups.Add(floatgroup);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
string xmlFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "test.xml";
if (File.Exists("test.xml"))
{
docklayoutmanager1.SaveLayoutToXml("test.xml");
}
else
{
using (File.Create("test.xml")) { }
docklayoutmanager1.SaveLayoutToXml("test.xml");
}
}
}
}
I have a document layout manager programmatically getting panels and controls which is having panels and controls in them.
While saving, I am achieving this with SaveLayoutToXml() for my panels and Serializing controls using bformatter.Serialize();.
since i have lot of panels and unique controls in them. I want to get the same controls back in same panels as it was before saving and serializing. Please provide me with a code to identify with a unique id for both panels and controls.
And do I have any integer id to which I can assign GUID as BindableName does not work with it.
Thanks
Desh
Create your panels programmatically and and them to your xaml file at run time.
UserC = new UserC();
DocumentPanel dpanel = new DocumentPanel();
dpanel.Name = "OpenUC" + count;
dpanel.Caption = "Open User Control";
dpanel.BindableName = "OpenUC" + count;
var content = UserC;
dpanel.Content = content;
FloatGroup fGroup = new FloatGroup();
fGroup.FloatSize = new Size(500, 500);
fGroup.Items.Add(dpanel);
DockLayoutManager1.FloatGroups.Add(fGroup);
This is how to add a User Control, since nobody seems to be interested in helping, i searched and done something like this:
private FloatGroup CreateDocPanelFloatGroup(DocumentPanel dp)
{
FloatGroup floatGroup = new FloatGroup();
floatGroup.FloatSize = new Size(500, 500);
floatGroup.Items.Add(dp);
return floatGroup;
}
private void OpenUC_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
openUC = new OpenUC();
DocumentPanel dp = new DocumentPanel();
dp.Name = "OpenUC" + count;
dp.Caption = "Open User Control";
dp.BindableName = "OpenUC" + count;
var content = openUC;
dp.Content = content;
DockLayoutManager1.FloatGroups.Add(CreateDocPanelFloatGroup(dp));
}
i want to get all my phone contacts in a list so i'm using those libraries and the *ID_CAP_CONTACTS* is checked in the WMAppManifest.xaml
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using System.Windows.Input;
using Microsoft.Phone.Shell;
using Microsoft.Phone.UserData;
but in my code the ContactResultsData.DataContext is not found
public MainPage()
{
InitializeComponent();
Contacts objContacts = new Contacts();
objContacts.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(objContacts_SearchCompleted);
objContacts.SearchAsync(string.Empty, FilterKind.None, null);
}
void objContacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
List<CustomContact> listOfContacts = new List<CustomContact>();
foreach (var result in e.Results)
{
CustomContact contact = new CustomContact();
contact.DisplayName = result.DisplayName;
var number = result.PhoneNumbers.FirstOrDefault();
if (number != null)
contact.Number = number.PhoneNumber;
else
contact.Number = "";
listOfContacts.Add(contact);
}
ContactResultsData.DataContext = listOfContacts;
}
}
private void ContactResultsData_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Contact contact = ContactResultsData.SelectedItem as Contact;
if (contact != null)
{
CustomContact customContact = new CustomContact(contact);
}
}
what is the problem what it needs please
i forget to add the ListBox ContactResultsData
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Height="Auto" Width="Auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,10" >
<TextBlock Name="ContactResultsLabel" Text="results are loading..." Style="{StaticResource PhoneTextLargeStyle}" TextWrapping="Wrap" />
<ListBox Name="ContactResultsData" ItemsSource="{Binding}" Height="436" Margin="12,0" SelectionMode="Multiple" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="ContactResults" FontSize="{StaticResource PhoneFontSizeMedium}" Text="{Binding Path=DisplayName, Mode=OneWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
i want to add search panel in my datagrid, there is no error in code but if i enter any value it is not showing any output. Can you please answer my question. my code is here below:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core"
dx:ThemeManager.ThemeName="MetropolisDark"
Title="MainWindow" Height="350" Width="525" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
ResizeMode="CanMinimize" mc:Ignorable="d" Loaded="Window_Loaded" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors">
<Grid Background="#FF333333" >
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="1" Height="28" HorizontalAlignment="Left" Margin="41,12,0,0" x:Name="textBlock1" Text="Type here" VerticalAlignment="Top" Width="71" />
<TextBox Grid.Row="1" HorizontalAlignment="Left" Margin="139,12,0,246" x:Name="textBox1" Width="233" TextWrapping="NoWrap" TextChanged="textBox1_TextChanged" />
<ListBox Grid.Row="1" Background="LightYellow" Visibility="Collapsed" Height="33" HorizontalAlignment="Left" Margin="220,45,0,0" Name="listBox1" VerticalAlignment="Top" Width="202" />
</Grid>
</Window>
public partial class MainWindow : Window
{
//object used for update data
DataClasses1DataContext objContext = new DataClasses1DataContext();
//object used to update selected row data
Assignment student = null;
IEnumerable eventt_grp1;
public MainWindow()
{
InitializeComponent();
//Database context
//StudentDBDataContext objContext = new StudentDBDataContext();
//Linq to SQL: this is like sql select query
//std is table alias
//objContext.StudentDetails is table from data is seleted
//var result: behaves like DataSet/DataTable
List<Assignment> a = new List<Assignment>();
eventt_grp1 = a.Select(r => new { r.assignment_title }).ToList();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
//Show message if it has rows
}
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string typedstring= textBox1.Text;
List<string> autolist= new List<string>();
foreach(string b in eventt_grp1)
{
if(!string.IsNullOrEmpty(textBox1.Text))
{
if(b.StartsWith(typedstring))
{
autolist.Add(b);
}
}
}
if(autolist.Count>0)
{
listBox1.ItemsSource = autolist;
listBox1.Visibility = Visibility.Visible;
}
else if (textBox1.Text.Equals (""))
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
else
{
listBox1.Visibility = Visibility.Collapsed;
listBox1.ItemsSource = null;
}
}
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (listBox1.ItemsSource != null)
{
listBox1.Visibility = Visibility.Collapsed;
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
if (listBox1.SelectedIndex != -1)
{
textBox1.Text = listBox1.SelectedItem.ToString();
textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
}
}
I have attached image of it too! Thank You !
I suggest you to debug flow. It is possible that autolist is empty. Also use this to update datasource:
listBox1.DataSource = null;
listBox1.DataSource = myList;
Hope it helps
EDIT:
hint -> format your code!