Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.

Is there a way to modify a UIElement's contents?
I have something like this:

System.IO.FileStream rdr = System.IO.File.OpenRead(xamlFilePath);
System.Windows.UIElement uie = (System.Windows.UIElement)System.Windows.Markup.XamlReader.Load(rdr);



And when I run the debugger and add uie to the "Watch" window, it gives me the following:

[-]uie
[-]System.Windows.Controls.Textbox          {System.Windows.Controls.Textbox:Title}
<some stuff...>
Text                                        "Title"


Now I need to be able to do two things: (1) read the Text in the textbox, and (2) modify it whenever I want.
I was hoping for something in the lines of:
{
Textbox tb = (Textbox)uie.GetChild();
tb.Text = "New Title"
uie.SetChild(tb);
}
, but it does not work like that. If anyone can point me to the method that performs this function I'd really appreciate it.

Thanks.
Posted

1 solution

Here's some sample code:

C#
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    string xaml = @"<StackPanel xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""><TextBox Width=""150"" Height=""25"" /></StackPanel>";
    var ui = System.Windows.Markup.XamlReader.Parse(xaml) as FrameworkElement;
    var textBox = VisualTreeHelper.GetChild(ui, 0) as TextBox;
    textBox.Text = DateTime.Now.ToLongTimeString();

    mainGrid.Children.Add(ui);
}


mainGrid is a Grid control. The dynamically loaded content is added to this Grid.
 
Share this answer
 
v2
Comments
Software_Guy 25-Oct-10 21:06pm    
Thank you for your reply. Unfortunately, I'm using C# and don't know much about VB. Could you help me with the translation of just the next line?

var textBox = VisualTreeHelper.GetChild(ui, 0) as TextBox;

The best I'm coming up with is:
System.Windows.Forms.TextBox tb = (System.Windows.Forms.TextBox)System.Windows.Media.VisualTreeHelper.GetChild(uie, 0);

, and it's not compiling (Error 8: Cannot convert type 'System.Windows.DependencyObject' to 'System.Windows.Forms.TextBox').
Nish Nishant 25-Oct-10 21:07pm    
Uhm, what I posted is C# code. So you don't need to do any conversion.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900