I want to change textblock value depending on the slider value each time I change it. But it shouldn't be done in XAML, because I want to make manipulations over return data. But the text in the textblock is not changed. Where is the problem?
My XAML is:
<Slider x:Name="slider" Value="0.2" SmallChange="0.1" Minimum="0" Maximum="10"
HorizontalAlignment="Left" Margin="26,208,0,0" VerticalAlignment="Top"
Width="195" ValueChanged="Slider_ValueChanged"/>
my WP 8 page code is:
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Slider slider = e.OriginalSource as Slider;
if (slider != null)
{
sliderTBk.Text = slider.Value.ToString();
}
}
Use thi XAML without CodeBehind
<TextBlock x:Name="sliderTBk" Text="{Binding Value, ElementName=slider" />
This should work.
And dont forget to remove the ValueChanged Eventhandler.
If you have to use CodeBehind:
private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (slider != null)
{
sliderTBk.Text = slider.Value.ToString();
}
}
Try this becuse i think that
Slider slider = e.OriginalSource as Slider;
hides your control x:name="slider"
Related
I would like to change the textbox default textcolor to the original default color after item is added to a list.
XAML
<TextBox Name="AddLocationTextBox" Text="{Binding Path=AddLocationName, UpdateSourceTrigger=PropertyChanged}"
LostFocus="AddLocationTextBox_LostFocus" GotFocus="AddLocationTextBox_GotFocus" HorizontalAlignment="Left" Height="23" Margin="10,37,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="285">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding AddLocationCommand}" />
</TextBox.InputBindings>
</TextBox>
Code behind in View
public LocationManagerView()
{
InitializeComponent();
AddLocationTextBox.Foreground = Brushes.Gray;
}
private void AddLocationTextBox_GotFocus(object sender, RoutedEventArgs e)
{
AddLocationTextBox.Text = string.Empty;
AddLocationTextBox.Foreground = Brushes.Black;
}
private void AddLocationTextBox_LostFocus(object sender, RoutedEventArgs e)
{
AddLocationTextBox.Foreground = Brushes.Gray;
}
ViewModel
public RelayCommand AddLocationCommand { get; private set; }
private void AddLocation()
{
if ( AddLocationName != null)
{
Locations.Add(new Location()
{
Name = AddLocationName,
});
AddLocationName = "Enter New Location";
Keyboard.ClearFocus();
////change textcolor to gray////
}
else
{
return;
}
}
It's after AddLocationName is set again to "Enter New Location" I want to change the textcolor back to gray.
Looks like the Keyboard.ClearFocus() doesn't call the LostFocus method in the View.
Any Idea how I make this work?
If you just want to change the foreground of your TextBox to gray, instead of tying to force AddLocationTextBox to lose it's focus, you should change the foreground manually (i.e. use AddLocationTextBox.Foreground = Brushes.Gray instead of Keyboard.ClearFocus()).
If you're looking for a way to force currently focused element to lose focus, then you can use below code instead of Keyboard.ClearFocus() :
UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;
elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
How could I unmasked and masked the password inside the passwordBox whenever I click the checkBox? I'm using C# WPF template.
Here is my .XAML code:
<PasswordBox x:Name="passwordBox_password" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Height="25" />
<CheckBox x:Name="checkBox_showPassword" Grid.Row="3" Grid.Column="1" Margin="5,0,5,5" Content="show password" Checked="checkBox_showPassword_Checked" Unchecked="checkBox_showPassword_Unchecked" />
Here is my .CS code:
private void checkBox_showPassword_Checked(object sender, RoutedEventArgs e)
{
// what to do here ?
}
private void checkBox_showPassword_Unchecked(object sender, RoutedEventArgs e)
{
// what to do here ?
}
Or is there another way to do it in WPF?
It's very simple to do that.
First you should to add the value PasswordChar in your PasswordBox:
<PasswordBox Name="PasswordHidden" PasswordChar="•"/>
Next under the PasswordBox tag you should to add a TextBox with Visibility value setted to Hidden:
<TextBox Name="PasswordUnmask" Visibility="Hidden"/>
And a trigger to show / hide the password, for example a simple text or a button. In my case I'm using a simple text.
<TextBlock Name="ShowPassword"/>
Next you need to add 3 different events in the trigger element, for example (this is valid for TextBlock or Image, if you want to use a Button you should to choose another events):
<TextBlock x:Name="ShowPassword" Text="SHOW" PreviewMouseDown="ShowPassword_PreviewMouseDown" PreviewMouseUp="ShowPassword_PreviewMouseUp" MouseLeave="ShowPassword_MouseLeave"/>
The events are PreviewMouseDown PreviewMouseUp and MouseLeave but you can choose the appropriate event for your situation.
Now in your code you need to program the functions:
private void ShowPassword_PreviewMouseDown(object sender, MouseButtonEventArgs e) => ShowPasswordFunction();
private void ShowPassword_PreviewMouseUp(object sender, MouseButtonEventArgs e) => HidePasswordFunction();
private void ShowPassword_MouseLeave(object sender, MouseEventArgs e) => HidePasswordFunction();
private void ShowPasswordFunction()
{
ShowPassword.Text = "HIDE";
PasswordUnmask.Visibility = Visibility.Visible;
PasswordHidden.Visibility = Visibility.Hidden;
PasswordUnmask.Text = PasswordHidden.Password;
}
private void HidePasswordFunction()
{
ShowPassword.Text = "SHOW";
PasswordUnmask.Visibility = Visibility.Hidden;
PasswordHidden.Visibility = Visibility.Visible;
}
The following link will bring you to the answer you are looking for my good sir. Mr Lamas did a great job of answering the how-to so I'd rather redirect you to the answer :)
showing password characters on some event for passwordbox
I recommend Using MahApps.Metro ... after installing it from nuget.org ... you must use it in the head of your xaml like this
xmlns:controls="http://metro.mahapps.com/winf/xaml/controls"
and then ... just use it's style for your PasswordBox control
<PasswordBox Style="{StaticResource MetroButtonRevealedPasswordBox}" />
you can even change the content for the show icon using the controls:PasswordBoxHelper.RevealButtonContent attached property
I have this simple slider project. I wanna show slider value in TextBox.
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<TextBox x:Name="sliderValue" HorizontalAlignment="Stretch" VerticalAlignment="Top" />
<Slider x:Name="slider" Minimum="0" Maximum="20" Value="5" ValueChanged="slider_ValueChanged"/></Grid>
// Constructor
public MainPage()
{
InitializeComponent();
}
private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
var slider = sender as Slider;
string value = string.Format("{0}", slider.Value);
sliderValue.Text = value;
}
In last line I am getting this error:
System.NullReferenceException: Object reference not set to an instance of an object.
at slider_test.MainPage.slider_ValueChanged(Object sender, RoutedPropertyChangedEventArgs`1 e)
at .......
Could anyone explain me what is the problem? Thank you.
You can do it using XAML by Binding slider value to TextBlock text.
<Slider x:Name="SliderValueText" ValueChanged="SliderValueText_ValueChanged"
VerticalAlignment="Top"
Width="440"
Minimum="0"
Maximum="20"
Value="5" />
<TextBlock Height="30"
Text="{Binding Value, ElementName=SliderValueText}"
VerticalAlignment="Top"
HorizontalAlignment="Center" />
private void SliderValueText_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
string value = string.Format("{0}", e.NewValue);
MessageBox.Show(value);
}
It is one of the option. Here you need the slider value. So I am storing in the variable "value". That's what I am displaying in MessageBox. But it is least case to try...
I am not sure but may be this will help you.
private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Dispatcher.BeginInvoke(() =>
{
string value = string.Format("{0}", e.NewValue);
sliderValue.Text = value;
});
}
In this way use e.NewValue for polling changing a value:
private void slider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
Debug.WriteLine("Value changed and value is " + e.NewValue.ToString());
}
But for labels simply use XAML bindings:
<TextBlock x:Name="someLabel"
Text="{Binding ElementName=slider, Path=Value}"
/>
I've a list of data,
Each row will show a data and will have a button, when i click the data shown i want give some data to the previous page and when i click the button in the same row i want to send that same data to next page.
My Xaml code,
<ListBox x:Name="List" HorizontalAlignment="Left" Height="612" Margin="6,7,0,0" VerticalAlignment="Top" Width="443" SelectionChanged="List_SelectionChanged_1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Width="420" Height="50">
<TextBlock x:Name="tbName" Width="400" Height="44" FontSize="22" FontWeight="Bold" Text="{Binding Name}" />
<Button x:Name="DetailButton" Height="44" Width="20" Content=">" FontWeight="Bold" Click="DetailButton_Click_1"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and the code for List_SelectionChanged_1 event handler is,
private void List_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/Page1.xaml",selectedItemData);
}
and my DetailButton_Click_1 event handler is,
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
Things work fine for *List_SelectionChanged_1*, but i get an exception while executing
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
of the DetailButton_Click_1 , i get an exception a null exception,
An exception of type 'System.NullReferenceException' occurred in ExpenseApp.DLL but was not handled in user code
What should i do make it work?
The underlying problem is that the sender of the button click event is the button, not the ListBox.
Also note that clicking the button on your data template will not necessarily select that item in the list. Try to grab the clicked item's data context and use that instead of .SelectedItem
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
var clickedUIElement = sender as Button;
if (null == clickedUIElement) { Return; }
Display selectedItemData = clickedUIElement.DataContext as Display;
if(null != selectedItemData)
{
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
}
Your code, as it stands, will have a null reference since you can't cast a Button as a ListBox.
try verify if the selectvalue is null before execute the code:
private void DetailButton_Click_1(object sender, RoutedEventArgs e)
{
If ((sender as ListBox).SelectedValue != null){
Display selectedItemData = (sender as ListBox).SelectedValue as Display;
NavigationService.Navigate("/page3.xaml", selectedItemData);
}
}
I have created a registration form in silverlight 4, where i have a large number of text-boxes, in front of each text box i have placed a text-block as a required field validator, when any of the textbox left empty while loosing focus, the textblock placed in front of it must become red.
textboxes named textbox1, textbox2 ... and so as the textblocks
the problem is, i do not want code the specific method for each specific textbox, all i want to do is to complete such in just two three methods
here i did some coding which doesn't seems to be correct
private void textBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox) sender;
if (textbox.Text == "")
{
var textblock = "textblock" + textBox.Name.Remove(0,7);
TextblockColorChange(textblock);
}
}
private void TextblockColorChange(object sender)
{
var textblock = (TextBlock) sender;
textblock.Foreground= new SolidColorBrush(Colors.Red);
}
please suggest some better way to do so..
I'd create a UserControl that contains the TextBlock and the TextBox and use this UserControl everywhere you currently have the TextBlock and TextBox combination. Then this Usercontrol would have the LostFocus logic inside it and update the TextBlock appropriately. This prevents the need to figure out the right name of the control to update.
you need something like this,
XAML part:
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Orientation="Horizontal" Height="25">
<TextBox Width="150" LostFocus="TextBox_LostFocus"/>
<TextBlock Text="*" Foreground="#FF0000" VerticalAlignment="Center" Margin="10,0,0,0" Visibility="Collapsed"/>
</StackPanel>
</Grid>
C# Part:
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textbox = sender as TextBox;
if(textbox == null) return;
var stackPanel = textbox.Parent as StackPanel;
if(stackPanel == null) return;
var textBlock = stackPanel.Children.Where(a => a is TextBlock).FirstOrDefault();
if (textBlock == null) return;
if (string.IsNullOrEmpty(textbox.Text)) textBlock.Visibility = Visibility.Visible;
else textBlock.Visibility = Visibility.Collapsed;
}
Whilst I actually prefer Bills approach (although I'd be inclined to use a Templated Control) here is another alternative which is quite fun. In your xaml use this sort of markup:-
<TextBlock Text="Enter Value 1" Foreground="{Binding Tag, ElementName=textBox1, TargetNullValue=Black}" />
<TextBox x:Name="textBox1" LostFocus="txt_LostFocus" />
Your common txt_LostFocus can look like this:-
private void txt_LostFocus(object sender, RoutedEventArgs e)
{
TextBox txt = ((TextBox)sender);
if (String.IsNullOrEmpty(txt.Text))
{
txt.Tag = new SolidColorBrush(Colors.Red);
}
else
{
txt.Tag = null;
}
}
var textblock = "textblock" + textBox.Name.Remove(0,7);
TextblockColorChange(textblock);
This code above will just send a string to TextblockColorChange()
You don't show any other code, but I'm guessing you want to do a FindControl or FindControl like search on that string before passing the result to your code.