Get TextBlock inside Button - c#

I have a Button with a TextBlock embedded inside. When the Button is clicked, I want to be able to fetch the TextBlock inside it and modify it's members.
Here is how my button is setup:
<Button Click="Select_Click" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Padding="0,20,20,20">
<TextBlock Text="My text" FontSize="20" Style="{StaticResource TextBlockStyle}"/>
</Button>
In my code behind I want to be able to access the embedded TextBlock:
public void Select_Click(object sender, RoutedEventArgs e)
{
// Get the `TextBlock` from `sender` here
}
I've taken a look at the visual tree of the Button but I'm not seeing the TextBlock. I called GetVisualChildren() on the Button but I only see a Grid and no way to get to the Textblock.

The content of the Button is stored in its Content property and in your case, the TextBlock is the content of the Button.
public void Select_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
TextBlock textBlock = (TextBlock)button.Content;
}

Just do some casting and it's pretty simple
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Establish_handlers();
}
void Establish_handlers()
{
Mybutton.Click += Mybutton_Click;
}
private void Mybutton_Click(object sender, RoutedEventArgs e)
{
Button clicked_button = (Button)sender;
TextBlock desired_text = (TextBlock)clicked_button.Content;
Textbox_Show_Button_Content.Text = desired_text.Text;
}
}
<StackPanel>
<Button x:Name="Mybutton">
<TextBlock>Hello</TextBlock>
</Button>
<TextBox x:Name="Textbox_Show_Button_Content"></TextBox>
</StackPanel>

Related

Problem with button designs. MaterialDesign, c#, wpf

My problem would be, I want to make a menu with MaterialDesign and I want the button style to change when I go to one of the menu items in the menu. However, when I overwrite the MaterialDesign style, I cannot reset it. I wanna make somethin like like this:enter image description here
Thats my menu code:
<Grid>
<StackPanel Orientation="Horizontal" Height="35" VerticalAlignment="Top" >
<Button x:Name="User_B" Content="Users" MinWidth="100" Click="User_B_Click"/>
<Button x:Name="Auto_B" Content="Auto" MinWidth="100" Click="Auto_B_Click"/>
<Button x:Name="Clien_B" Content="Client" MinWidth="100" Click="Clien_B_Click" />
<Button x:Name="Failure_B" Content="Failure" MinWidth="100" Click="Failure_B_Click"/>
<Button x:Name="Settings_B" Content="Settings" MinWidth="100" Click="Settings_B_Click"/>
</StackPanel>
<Frame x:Name="Main" Margin="0,35,0,0" NavigationUIVisibility="Hidden"/>
</Grid>
My c# code:
private void User_B_Click(object sender, RoutedEventArgs e)
{
Style selectstyle = new Style();
selectstyle.TargetType = typeof(Button);
selectstyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#303030"))));
selectstyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#d50000"))));
User_B.Style = selectstyle;
Auto_B.Style = null;
}
private void Auto_B_Click(object sender, RoutedEventArgs e)
{
Style selectstyle = new Style();
selectstyle.TargetType = typeof(Button);
selectstyle.Setters.Add(new Setter(Button.BackgroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#303030"))));
selectstyle.Setters.Add(new Setter(Button.ForegroundProperty, new SolidColorBrush((Color)ColorConverter.ConvertFromString("#d50000"))));
Auto_B.Style = selectstyle;
User_B.Style = null;
}
and this is how it looks now:enter image description here
First you need to do this in all of your pages :
MainWindow mw = null;
public Employees(MainWindow mw)
{
InitializeComponent();
this.mw = mw;
}
Create a null object for your MainWindow , than give a parameter to your Page method , then in the method , you declare the MainWindow like I show you in the code.
After you done with this , then you need to go to the MainWindow.xaml.cs and you have to do this:
public MainWindow()
{
InitializeComponent();
employees = new Employees(this);
Presenter.Content = employees;
}
Employees employees = null;
Create a null object for your Page , and in the MainWindow method you have to declare the Page like this.
After that , you just need a Loaded and an Unloaded event to your page :
private void Page_Loaded(object sender, RoutedEventArgs e)
{
mw.EmployeesButton.Background = (Brush)new BrushConverter().ConvertFrom("#006B60");
}
private void Page_Unloaded(object sender, RoutedEventArgs e)
{
mw.EmployeesButton.Background = (Brush)new BrushConverter().ConvertFrom("#009688");
}
You can use any color you want , I hope its helps :D

code generated control not found in code wpf

I created control in WPF from C# and find that control on button click but not found
public MainWindow()
{
InitializeComponent();
TextBox textBox = new TextBox();
textBox.Name = "childTextBox";
TextBoxes.Add(textBox);
StackPanelParent.Children.Add(textBox);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var findTextBox = (TextBox)this.FindName("childTextBox");
//it's give null
}
XAML Code
<StackPanel Margin="152,103,191,56">
<Label Name="Loader" Visibility="Collapsed">Loader</Label>
<Button Content="Click Me" HorizontalAlignment="Left" Margin="342,199,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>-->
<StackPanel Name="StackPanelParent">
</StackPanel>
<Button Click="Button_Click">Check</Button>
</StackPanel>
When you dynamically create a component they cannot be found by FindName unless you register them first like this:
public MainWindow()
{
InitializeComponent();
TextBox textBox = new TextBox();
textBox.Name = "childTextBox";
TextBoxes.Add(textBox);
StackPanelParent.Children.Add(textBox);
// register name
RegisterName(textBox.Name, textBox);
}

C# / WPF Unmask password inside the passwordBox

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

Hyperlinks in Xaml to navigate from one page to another

How can I create Hyperlinks in Xaml to navigate from one page to another page? I don't know actually how to use the hyperlink tags.
You can use RequestNavigate event to add a HyperLink class
Xaml:
<TextBlock>
<Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
Click here
</Hyperlink>
</TextBlock>
Code Behind:
private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
If you are looking for navigating to another page :
<StackPanel Grid.Row="1"
Margin="120,0,120,60">
<HyperlinkButton Content="Click to go to page 2" Click="HyperlinkButton_Click"/>
</StackPanel>
And handle it like :
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(BasicPage2));
}
And to move to external page : As mentioned by #Brainy

How to select an item from a listbox in windows phone?

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);
}
}

Categories

Resources