How to validate RichTextbox in WPF? I want to validate the text for email and email separator i.e. emails should be entered with a semicolon.
Xaml:
<StackPanel Orientation="Horizontal">
<RichTextBox x:Name="txtEmail" Style="{StaticResource ContentRichTextBox}"
ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" Margin="0,0,10,0">
<FlowDocument>
<Paragraph LineHeight="5"></Paragraph>
</FlowDocument >
</RichTextBox>
</StackPanel>
<StackPanel HorizontalAlignment="Center">
<TextBlock x:Name="txterrormessage" Width="300" Foreground="#FFE5572C" FontSize="14" Visibility="Hidden" TextWrapping="Wrap"></TextBlock>
</StackPanel>
<StackPanel HorizontalAlignment="Center" Margin="60,0,0,0">
<Button x:Name="BtnEmail" Style="{StaticResource ShortButtonStyle}" Content="NEXT" Margin="10" Command="{Binding CommandChanged}" CommandParameter="PROJECTS" Click="BtnEmail_Click"/>
</StackPanel>
This is my code:
private void BtnEmail_Click(object sender, RoutedEventArgs e)
{
string richText = new TextRange(txtEmail.Document.ContentStart, txtEmail.Document.ContentEnd).Text;
if (!Regex.IsMatch(richText, #"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
{
txterrormessage.Text = "Enter a valid email";
txterrormessage.Visibility = System.Windows.Visibility.Visible;
}
else
{
txterrormessage.Visibility = System.Windows.Visibility.Hidden;
}
if (!Regex.IsMatch(richText, #"^((\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*)\s*[;]{0,1}\s*)+$"))
{
txterrormessage.Text = "Separate emails with ;";
txterrormessage.Visibility = System.Windows.Visibility.Visible;
}
}
The code doesnt seem to work....How to validate?
Thanks
The simplest way I've seen to do this is
private void OnVerifyEmail()
{
var recipients = richText.Split(';', StringSplitOptions.RemoveEmptyEntries);
var validator = new System.ComponentModel.DataAnnotations.EmailAddressAttribute();
foreach (var recipient in recipients)
{
var isValid = validator.IsValid(recipient.Trim());
if(!isValid)
{
// do your thing here
}
}
}
format your richText before validation:
richText = Regex.Replace(richText, #"(\n|\r)", "", RegexOptions.Multiline);
Edit:
This is the whole method and probably what you're looking for:
private void BtnEmail_Click(object sender, RoutedEventArgs e)
{
string richText = new TextRange(txtEmail.Document.ContentStart, txtEmail.Document.ContentEnd).Text;
richText = Regex.Replace(richText, #"(\n|\r)", "", RegexOptions.Multiline);
richText = Regex.Replace(richText, #"( ;|; )", ";", RegexOptions.Multiline);
txterrormessage.Visibility = System.Windows.Visibility.Hidden;
if (!Regex.IsMatch(richText, #"^[\W]*([\w+\-.%]+#[\w\-.]+\.[A-Za-z]{2,4}[\W]*,{1}[\W]*)*([\w+\-.%]+#[\w\-.]+\.[A-Za-z]{2,4})[\W]*$"))
{
string[] emails = Regex.Split(richText, ";", RegexOptions.Multiline);
foreach (string item in emails)
{
if (string.IsNullOrEmpty(item))
continue;
if (!Regex.IsMatch(item, #"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
txterrormessage.Text = item + " is not a valid email address";
txterrormessage.Visibility = System.Windows.Visibility.Visible;
break;
}
}
if (string.IsNullOrEmpty(txterrormessage.Text))
{
txterrormessage.Text = "Separate emails with ; ";
txterrormessage.Visibility = System.Windows.Visibility.Visible;
}
}
}
Related
I have an audio file in mp3 format, that internally I convert into WAV, when everything is done, I send it to the AI. I notice, that the time of transcription varies depending on different factors (length of audio, the region of your service, latency, internet speed, etc).
So how can I add a progress bar to my application, that keeps track accurately, and display the percentage?
I was researching, and I found a method that does this, but for files being uploaded to Azure Blob, I think is easier because you can calculate the file.size. and length.
What about transcriptions, that there is no way for us to determine things?
private async void AzureActionAsync(object obj)
{
var str = obj as string;
if (string.IsNullOrEmpty(str))
{
return;
}
switch (str)
{
case "AudioTranscription":
const string ext = ".wav";
var dlg = new OpenFileDialog
{
DefaultExt = ".mp3",
Filter = "Audio files (.mp3)|*.mp3"
};
var res = dlg.ShowDialog();
if (res! == true)
{
var AudioName = Path.GetFileNameWithoutExtension(dlg.SafeFileName);
var projectPath = Directory.GetParent(Directory.GetCurrentDirectory())?.Parent?.Parent?.FullName;
var FoderName = Path.Combine(projectPath!, "Audios");
var filePath = Path.Combine(FoderName, $"{AudioName}{ext}");
using var mp3 = new Mp3FileReader(dlg.FileName);
using var ws = WaveFormatConversionStream.CreatePcmStream(mp3);
WaveFileWriter.CreateWaveFile(filePath, ws);
await ConvertToTextAsync(filePath);
}
break;
}
}
private async Task ConvertToTextAsync(string FilePath)
{
// Configure speech service
var config = SpeechConfig.FromSubscription(Config.Constants.AZURE_KEY, Config.Constants.AZURE_REGION);
// Configure speech recognition
var taskCompleteionSource = new TaskCompletionSource<int>();
using var audioConfig = AudioConfig.FromWavFileInput(FilePath);
using var speechRecognizer = new SpeechRecognizer(config, audioConfig);
speechRecognizer.Recognizing += SpeechRecognizer_Recognizing;
speechRecognizer.Recognized += SpeechRecognizer_Recognized;
speechRecognizer.SessionStarted += SpeechRecognizer_SessionStarted;
speechRecognizer.SessionStopped += SpeechRecognizer_SessionStopped;
await speechRecognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);
Task.WaitAny(new[] { taskCompleteionSource.Task });
await speechRecognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
}
private void SpeechRecognizer_SessionStopped(object? sender, SessionEventArgs e)
{
var sb = new StringBuilder();
foreach (var item in Words)
{
sb.Append(item);
}
BackgroundClipboard.SetText(sb.ToString());
if (!string.IsNullOrEmpty(BackgroundClipboard.GetText()))
{
Application.Current.Dispatcher.Invoke(() =>
{
var spellWindow = new SpellCheckWindow();
spellWindow.ShowDialog();
});
}
}
private void SpeechRecognizer_SessionStarted(object? sender, SessionEventArgs e)
{
}
private void SpeechRecognizer_Recognized(object? sender, SpeechRecognitionEventArgs e)
{
if (e.Result.Reason == ResultReason.RecognizedSpeech)
{
foreach (var item in e.Result.Text)
{
Words.Add(item);
}
}
}
private void SpeechRecognizer_Recognizing(object? sender, SpeechRecognitionEventArgs e)
{
}
}
<Border Background="#272537" CornerRadius="20">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<Button
HorizontalAlignment="Right"
materialDesign:RippleAssist.Feedback="Transparent"
Background="{x:Null}"
BorderBrush="{x:Null}"
Command="{Binding ExitCommand}"
Focusable="False">
<materialDesign:PackIcon Kind="Close" />
</Button>
<ItemsControl Grid.Row="1" ItemsSource="{Binding Tiles}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Margin="40" Columns="2" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<syncfusion:SfHubTile Background="{Binding TileColor}" IsEnabled="{Binding IsTileActive}">
<behaviors:Interaction.Triggers>
<behaviors:EventTrigger EventName="Click">
<behaviors:InvokeCommandAction
Command="{Binding TileCommand}"
CommandParameter="{Binding TileTitle}"
PassEventArgsToCommand="True" />
</behaviors:EventTrigger>
</behaviors:Interaction.Triggers>
<Label
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Content="{Binding TileIcon}"
FontFamily="{StaticResource Material}"
FontSize="120"
Foreground="White" />
</syncfusion:SfHubTile>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Border>
and where in my UI I can thank you for the help this
I have successfully create a multilanguage application based from here. I was great when able to change language.
Now I have stuck in this situation. My application is operating with hardware. So there is one screen that having interaction with hardware and display status textblock. The message will be variant depend on the response from hardware e.g. "Please wait..", "Scan your ID into scanner", "Scan complete", "Profile identified, continue with transaction".
How do this variant can be display in multilingual into single textblock?
Assuming the textblock will be naming TbxStatus.Text. How do I set the message in ResourceDictionary file and how do I handle which resource string key that it should take?
EDITED [WHAT HAVE I TRIED]
This is the code that I've write to switch language and show based from resources dictionary:-
App.cs
public static String Directory;
public static App Instance;
public static event EventHandler LanguageChangedEvent;
public App()
{
// Initialize static variables
Instance = this;
Directory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Instance.SetLanguageResourceDictionary(Instance.GetLocXAMLFilePath("en-US"));
}
public static void LoadLanguageLocalization()
{
try
{
ViewModel.AppConfigViewModel.LocalizationProperty.LangLoc = new List<ApplicationModel.LanguageLocalization>
{
new ApplicationModel.LanguageLocalization { LanguageID = 1, CountryCode = "ms-MY", LanguageName = "Bahasa Malaysia" },
new ApplicationModel.LanguageLocalization { LanguageID = 2, CountryCode = "en-US", LanguageName = "English" },
new ApplicationModel.LanguageLocalization { LanguageID = 3, CountryCode = "zh-CN", LanguageName = "Chinese" },
new ApplicationModel.LanguageLocalization { LanguageID = 4, CountryCode = "ta-IN", LanguageName = "Tamil" }
};
}
catch (Exception ex)
{
LogEvents($"[App] Exception on LoadLanguageLocalization. Message-{ex.Message}. Stack Trace-{ex.StackTrace}", EventLogEntryType.Error);
ViewModel.AppConfigViewModel.LocalizationProperty.LangLoc = null;
}
}
public void SwitchLanguage(string inFiveCharLang)
{
if (System.Globalization.CultureInfo.CurrentCulture.Name.Equals(inFiveCharLang))
return;
var ci = new System.Globalization.CultureInfo(inFiveCharLang);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
SetLanguageResourceDictionary(GetLocXAMLFilePath(inFiveCharLang));
LanguageChangedEvent?.Invoke(this, new EventArgs());
}
private string GetLocXAMLFilePath(string inFiveCharLang)
{
string locXamlFile = "Resources." + inFiveCharLang + ".xaml";
return Path.Combine(Directory, "Language", locXamlFile);
}
public void SetLanguageResourceDictionary(String inFile)
{
if (File.Exists(inFile))
{
// Read in ResourceDictionary File
var languageDictionary = new ResourceDictionary();
languageDictionary.Source = new Uri(inFile);
// Remove any previous Localization dictionaries loaded
int langDictId = -1;
for (int i = 0; i < Resources.MergedDictionaries.Count; i++)
{
var md = Resources.MergedDictionaries[i];
// Make sure your Localization ResourceDictionarys have the ResourceDictionaryName
// key and that it is set to a value starting with "Loc-".
if (md.Contains("LanguageDictionaryName"))
{
if (md["LanguageDictionaryName"].ToString().StartsWith("Lang-"))
{
langDictId = i;
break;
}
}
}
if (langDictId == -1)
{
// Add in newly loaded Resource Dictionary
Resources.MergedDictionaries.Add(languageDictionary);
}
else
{
// Replace the current langage dictionary with the new one
Resources.MergedDictionaries[langDictId] = languageDictionary;
}
}
}
SelectLanguage.cs
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
try
{
App.LogEvents($"[{PageTitle}] Loaded: Select language", System.Diagnostics.EventLogEntryType.Information);
BindingToPropertyControl();
}
catch (System.Exception ex)
{
string error = $"[{PageTitle}] Exception on Page_Loaded. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
App.LogEvents(error, System.Diagnostics.EventLogEntryType.Error);
}
}
private void BindingToPropertyControl()
{
try
{
if (ViewModel.AppConfigViewModel.LocalizationProperty.LangLoc != null)
{
LanguagePack.ItemsSource = ViewModel.AppConfigViewModel.LocalizationProperty.LangLoc;
}
}
catch (System.Exception ex)
{
string error = $"[{PageTitle}] Exception on BindingToPropertyControl. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
App.LogEvents(error, System.Diagnostics.EventLogEntryType.Error);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
ScreenTimer.Stop();
Button btn = (Button)sender;
string LangCode = btn.Tag.ToString();
App.LogEvents($"[{PageTitle}] Selecting language: {LangCode}", System.Diagnostics.EventLogEntryType.Information);
App.Instance.SwitchLanguage(LangCode.ToString());
Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(delegate ()
{
NavigationService.Navigate(new Uri(ApplicationModel.NaviModel.NaviSelectOptions, UriKind.RelativeOrAbsolute));
}));
}
catch (System.Exception ex)
{
string error = $"[{PageTitle}] Exception on Button_Click. Message: {ex.Message}. StackTrace: {ex.StackTrace}";
App.LogEvents(error, System.Diagnostics.EventLogEntryType.Error);
}
}
SelectLanguage.xaml
<ScrollViewer x:Name="ScrollLanguage" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden">
<WrapPanel Height="Auto" Width="{Binding ElementName=ScrollLanguage, Path=ViewportWidth}">
<ItemsControl Name="LanguagePack">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="0,20" VerticalAlignment="Stretch" Width="{Binding ElementName=ScrollLanguage, Path=ViewportWidth}">
<Button Click="Button_Click" Tag="{Binding CountryCode}" Content="{Binding LanguageName}" VerticalAlignment="Center" Height="150" FontSize="60" Background="#FF1A5C9E" BorderBrush="{x:Null}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</WrapPanel>
</ScrollViewer>
SelectOptions.xaml
<TextBlock x:Name="tbTitle" TextWrapping="Wrap" Text="{StaticResource ResourceKey=SelectMerchant_Title}" FontSize="100" TextAlignment="Center" Padding="0,0,0,50" Foreground="White"/>
<Button x:Name="btnEatIn" Content="{StaticResource ResourceKey=SelectMerchant_Opt1}" VerticalAlignment="Center" Height="150" FontSize="60" Background="#FF057A5A" BorderBrush="{x:Null}"/>
<Button x:Name="btnEatIn" Content="{StaticResource ResourceKey=SelectMerchant_Opt2}" VerticalAlignment="Center" Height="150" FontSize="60" Background="#FF057A5A" BorderBrush="{x:Null}"/>
Resources.en-US.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<!-- The name of this ResourceDictionary. Should not be localized. -->
<sys:String x:Key="LanguageDictionaryName" Localization.Comments="$Content(DoNotLocalize)">Lang-en-US</sys:String>
<!-- Localization specific styles -->
<FlowDirection x:Key="FlowDirection_Default" Localization.Comments="$Content(DoNotLocalize)">LeftToRight</FlowDirection>
<!--<FlowDirection x:Key="FlowDirection_Reverse" Localization.Comments="$Content(DoNotLocalize)">RightToLeft</FlowDirection>-->
<!-- SELECT ORDER TYPE -->
<sys:String x:Key="SelectMerchant_Title">Self-Service Kiosk</sys:String>
<sys:String x:Key="SelectMerchant_Opt1">Register new applicant</sys:String>
<sys:String x:Key="SelectMerchant_Opt2">Meal Application</sys:String>
</ResourceDictionary>
Back to what I'm facing, I can show different language by using resource key, but how to I display message or status which is dynamically (not static) into the display in multi-language?
Example, on validation screen, I have one TextBlock and currently I'm subscribe the event raise from hardware. How to show the status based from language that has been selected?
.
<StackPanel VerticalAlignment="Top" Margin="120,180,120,0" Grid.Row="1">
<TextBlock x:Name="tbGeneralStatus" TextWrapping="Wrap" Text="Please wait..." TextAlignment="Center" FontSize="50" Foreground="Yellow"/>
</StackPanel>
tbGeneralStatus.Text will show "Please wait..", "Scan your ID into scanner", "Scan complete", "Profile identified, continue with transaction" from delegate event from Barcode Scanner class.
I think you need to look a little into MVVM to make things easier with WPF. It takes some effort at the beggining, but its absolutely worth. I thought you were stucked only on how to receive and translate the status, so I'll try to give more info after looking at the code.
A quick guidance, based on Enum localization but not verified in dept.
You need a viewmodel to act as datacontext of the window you want to update. It has to implement INotifyPropertyChange interface to update the status in live.
class YourWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private string _statusText = string.Empty;
public string StatusText
{
get { return _statusText; }
set
{
_statusText = value;
OnPropertyChanged("StatusText");
}
}
public void YourMessageHandler(Status newStatus)
{
StatusText = GetLocalizedStatusText(newStatus);
}
private string GetLocalizedStatusText(Status newStatus)
{
switch (newStatus)
{
case Status.Wait: return Resources.StatusWaiting;
case Status.Continue: return Resources.StatusContinue;
case Status.Scan: return Resources.StatusScanId;
default: return string.Empty;
}
}
}
public enum Status
{
Wait,
Scan,
Continue
}
To bind to your window, make it like this:
<Window.DataContext>
<local:YourWindowViewModel/>
</Window.DataContext>
and change your TextBlock control to bind to the StatusText on the viewmodel
<StackPanel VerticalAlignment="Top" Margin="120,180,120,0" Grid.Row="1">
<TextBlock TextWrapping="Wrap" Text="{Binding StatusText}" TextAlignment="Center" FontSize="50" Foreground="Yellow"/>
</StackPanel>
Note that as I don't know your delegate/msgHandler format, I have put a generic "YourMessageHandler" method which receive the changing status
My implementation of an ObservableCollection does not update my Grid and I don't know why:
The first XAML-Window 'UserControlStaff.xaml' displays the Grid where the user data can be seen. The second XAML-Window allows to add users and is called 'CreateUser.xaml'.
The code behind the XAML-Windows is attached to this post as well.
My Code goes as follows:
[XAML] UserControlStaff.xaml
<UserControl x:Class="MyApp.UserControlStaff"
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"
d:DesignHeight="300" d:DesignWidth="786">
<StackPanel x:Name="spStaff" Orientation="Vertical" Visibility="Visible">
<Button Background="Azure" Click="btnCreateUser_Click" HorizontalAlignment="Left" Width="786" Height="40">
<Bold>Mitarbeiter hinzufügen</Bold></Button>
<ScrollViewer MaxHeight="504">
<DataGrid Background="#DBDB72" ItemsSource="{Binding UserDataObject}" CanUserAddRows="false" Width="786" />
</ScrollViewer>
</StackPanel>
</UserControl>
[Code] UserControlStaff.xaml.cs
namespace MyApp
{
/// <summary>
/// Interaktionslogik für UserControlStaff.xaml
/// </summary>
public partial class UserControlStaff : UserControl
{
ObservableCollection<User> mUserDataObject = new ObservableCollection<User>();
public ObservableCollection<User> UserDataObject
{
get
{
return mUserDataObject;
}
}
public UserControlStaff()
{
InitializeComponent();
DataContext = this;
try
{
string connectionString = ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.ConString"].ConnectionString;
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
queryString = "SELECT ID, username AS Username, Password AS Passwort, (SELECT role FROM Roles WHERE ID = t1.role) AS Rolle FROM Users t1 ORDER BY ID";
SqlCommand cmd = new SqlCommand(queryString, connection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Users");
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
int pID = 0;
string pUsername = "";
string pPassword = "";
string pRole = "";
foreach (DataColumn col in dt.Columns)
{
if (col.ToString().Trim() == "ID")
{
pID = int.Parse(row[col].ToString());
}
else if (col.ToString().Trim() == "Username")
{
pUsername = row[col].ToString();
}
else if (col.ToString().Trim() == "Passwort")
{
pPassword = row[col].ToString();
}
else if (col.ToString().Trim() == "Rolle")
{
pRole = row[col].ToString();
}
}
// Show Users DB table in MainWindow
mUserDataObject.Add(new User { ID = pID, Username = pUsername, Password = pPassword, Role = pRole });
}
// Show Users DB table in MainWindow
//XAML Grid: Name="gridUsers"
//CS Code: gridUsers.DataContext = dt.DefaultView;
}
}
catch {
throw;
}
}
private void btnCreateUser_Click(object sender, RoutedEventArgs e)
{
CreateUser popup = new CreateUser();
popup.Show();
}
private void UpdateUserData()
{
// implement
}
private void DeleteUserData()
{
// implement
}
}
}
[XAML] CreateUser.xaml
<Window x:Class="MyApp.CreateUser"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Mitarbeiter hinzufügen" Height="300" Width="400">
<Grid>
<Label Content="Username" HorizontalAlignment="Left" Margin="10,44,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
<Label Content="Passwort" HorizontalAlignment="Left" Margin="10,88,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
<Label Content="Rolle" HorizontalAlignment="Left" Margin="10,132,0,0" VerticalAlignment="Top" Width="120" Height="30"/>
<TextBox HorizontalAlignment="Left" Height="30" Margin="150,44,0,0" TextWrapping="Wrap" Name="TextBoxUsername" Text="{Binding Path=Username}" VerticalAlignment="Top" Width="180"/>
<TextBox HorizontalAlignment="Left" Height="30" Margin="150,88,0,0" TextWrapping="Wrap" Name="TextBoxPassword" Text="{Binding Path=Password}" VerticalAlignment="Top" Width="180"/>
<ComboBox HorizontalAlignment="Left" Height="30" Margin="150,132,0,0" VerticalAlignment="Top" Width="180" Loaded="ComboBox_Loaded" SelectionChanged="ComboBox_SelectionChanged"/>
<Button Click="btnSaveUserData_Click" Content="Speichern" HorizontalAlignment="Left" Margin="217,219,0,0" VerticalAlignment="Top" Height="30" Width="75"/>
<Button Click="btnCloseWindow_Click" Content="Abbrechen" HorizontalAlignment="Left" Margin="297,219,0,0" VerticalAlignment="Top" Height="30" Width="75"/>
</Grid>
</Window>
[Code] CreateUser.xaml.cs
namespace MyApp
{
/// <summary>
/// Interaktionslogik für CreateUser.xaml
/// </summary>
public partial class CreateUser : Window
{
User userObject;
public CreateUser()
{
InitializeComponent();
this.userObject = new User();
}
private void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
// ToDO: Rollenzuweisung automatisieren aus Datenbanktabelle MyApp.Roles
List<string> data = new List<string>();
data.Add("Chef");
data.Add("Restaurantmitarbeiter");
data.Add("Fahrer");
// ... Get the ComboBox reference.
var comboBox = sender as ComboBox;
// ... Assign the ItemsSource to the List.
comboBox.ItemsSource = data;
// ... Make the second item selected.
comboBox.SelectedIndex = 1;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// ... Get the ComboBox.
var comboBox = sender as ComboBox;
// ... Set SelectedItem as Window Title.
string value = comboBox.SelectedItem as string;
//this.Title = "Selected: " + value;
this.userObject.Role = value;
}
private void btnSaveUserData_Click(object sender, RoutedEventArgs e)
{
try
{
this.userObject.Username = TextBoxUsername.Text;
this.userObject.Password = TextBoxPassword.Text;
int UserRole;
// ToDO: Rollenzuweisung automatisieren aus Datenbanktabelle MyApp.Roles
if (this.userObject.Role == "Chef")
{
UserRole = 1;
}
else if (this.userObject.Role == "Restaurantmitarbeiter")
{
UserRole = 2;
}
else if (this.userObject.Role == "Fahrer")
{
UserRole = 3;
}
else
{
UserRole = 2; // Default UserRole is "Restaurantmitarbeiter"
}
if (this.userObject.Username.Trim() != "" && this.userObject.Password.Trim() != "")
{
CreateUserData(this.userObject.Username, this.userObject.Password, UserRole);
// ToDO: Update DataGrid in UserControlStaff
this.Close();
MessageBox.Show("Mitarbeiter hinzugefügt!");
} else {
MessageBox.Show("Bitte Username und Passwort eingeben.");
}
}
catch { throw; }
}
private void CreateUserData(string pUsername, string pPassword, int pRole)
{
string connectionString = ConfigurationManager.ConnectionStrings["MyApp.Properties.Settings.ConString"].ConnectionString;
string queryString = "INSERT INTO Users (ID, username, password, role) VALUES ((SELECT TOP 1 ID+1 FROM Users ORDER BY ID DESC), '" + pUsername + "', '" + pPassword + "', '" + pRole + "')";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(queryString, connection);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Users");
sda.Fill(dt);
string UserRole;
if (pRole == 1)
{
UserRole = "Chef";
}
else if (pRole == 2)
{
UserRole = "Restaurantmitarbeiter";
}
else if (pRole == 3)
{
UserRole = "Fahrer";
}
else
{
UserRole = "Restaurantmitarbeiter"; // Default UserRole is "Restaurantmitarbeiter"
}
// Add to Observable Collection
// ToDO
// mUserDataObject.Add(new User { ID = pID, Username = pUsername, Password = pPassword, Role = pRole });
}
private void btnCloseWindow_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
<TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" TextWrapping="Wrap" Visibility="Collapsed" ScrollViewer.VerticalScrollBarVisibility="Visible" Grid.Row="0" x:Name="sessionNoteContent" KeyUp="SaveNote">
private void SaveNote(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (String.IsNullOrWhiteSpace(sessionNoteContent.Text))
{
}
else
{
Class1 note = new Class1 ()
{
time1=timeElapsed,
Notes = sessionNoteContent.Text,
StartTime = sessionStartTime,
CurrentTimestamp = DateTime.Now,
TeamId = teamId,
};
repo.InsertSessionNote(note);
sessionNoteListData.Add(note);
sessionNoteContent.Text = "";
}
sessionNoteContent.Visibility = System.Windows.Visibility.Collapsed;
sessionNotesList.Visibility = System.Windows.Visibility.Visible;
}
I have handled key up event on my texbox. It slows down the display of characters when I type . Is there some wayto handle it. Working on wpf desktop application.
I am new to WPF.I have AutoCompleteBox.When i enter a search text,dropdownlist is populated.It contains items.I am able to selected those items and saved into databse through down or up arrow.But items are not visible.Here is my code
<AutoComplete:AutoCompleteBox Background="White" Tag="TagName..." Margin="0,0,28.8,0" Name="txtCustomTagName" BorderBrush="#FF104E8B" FontWeight="Normal" BorderThickness="1,1,0,1" FontSize="14" Foreground="#FF104E8B" TextChanged="txtCustomTagName_TextChanged" LostFocus="txtCustomTagName_LostFocus" PreviewTextInput="txtCustomTagName_PreviewTextInput" Populating="txtCustomTagName_Populating" >
<AutoComplete:AutoCompleteBox.ItemTemplate>
<DataTemplate>
<TextBlock />
</DataTemplate>
</AutoComplete:AutoCompleteBox.ItemTemplate>
</AutoComplete:AutoCompleteBox>
//Populated Event:-
private void txtCustomTagName_Populating(object sender, PopulatingEventArgs e)
{
string strFilePath = "";
string strNewFile = "";
strFilePath += #"../../FIXDictionaries/";
string typedString = txtCustomTagName.Text; ;
strNewFile = strFilePath + cmbFIXVerDataDictionary.Text + extension;
XDocument xmldoc = XDocument.Load(strNewFile);
List<string> tags = new List<string>();
IEnumerable<string> childNames = (from child in xmldoc.Element("fix").Element("fields").Descendants("field")
select child.Attribute("name").Value).Distinct().ToList();
foreach (string childName in childNames)
{
if (childName.StartsWith(typedString, StringComparison.InvariantCultureIgnoreCase))
{
tags.Add(childName);
}
}
txtCustomTagName.ItemsSource = tags;
}
}
How to do it?
I suppose the cause is you use ItemTemplate with empty TextBlock. Or don't use ItemTemplate at all or (in your case) replase it with <TextBlock Text="{Binding}" />