I want to access the element UserCodeTextBlock
in my code but for some reason I can't.
The idea is to show the TextBlock
and Button
, and after clicking the Button
they both go invisible and only the TextBox
is shown so i can change it's value.
This is all contained in a DataGridTemplateColumn
as shown in this code:
XAML
<DataGridTemplateColumn x:Name="user_codeColumn" Header="{x:Static p:Resources.User_user_code}" Width="SizeToHeader">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate x:Name="UserCodeTemplate">
<StackPanel x:Name ="UserCodeStack" Orientation="Horizontal" HorizontalAlignment="Right">
<TextBlock x:Name="UserCodeTextBlock" Text="{Binding UserCode, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay }" Visibility="Visible"/>
<TextBox x:Name="UserCodeTextBox" Text="{Binding UserCode, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay }" Visibility="Collapsed"/>
<Button Content="A" Click="UserCodeButton_Click"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
In my code I have an Event
that executes when the Button
is clicked. I'm trying to read XAML elements using a function that I found somewhere but it doesn't seem to work.
C#
public static T GetChildOfType<T>(this DependencyObject depObj)
where T : DependencyObject
{
if (depObj == null) return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null) return result;
}
return null;
}
private void UserCodeButton_Click(object sender, RoutedEventArgs e)
{
InitializeComponent();
var UserCodeTextBlock_ = this.user_codeColumn.GetChildOfType<DataTemplate>();
Button UserCodeButton_ = e.Source as Button;
UserCodeButton_.Visibility = Visibility.Hidden;
MessageBox.Show(Properties.Resources.CodeChanged, "", MessageBoxButton.OK);
}
I've tried a lot of things already but I couldn't make it work as I wish. Btw, I'm a newb in C# and WPF. Thanks in advance for any help!