StealthRT
StealthRT

Reputation: 10552

WPF change UserControl textblock from another window

Hey all I am new at WPF so here is my question:

How can I change the text in a TextBlock from my mainWindow when the textBlock is in the window named curTemp.xaml?

curTemp.xaml code:

public partial class curTemp : UserControl
    {
        public string _valTempChange
        {
            get { return middleForcastCurrentTemp.Text; }
            set { middleForcastCurrentTemp.Text = value; }
        }

        public curTemp()
        {
            InitializeComponent();
        }
    }

Xaml of the above UserControl:

<Grid>
        <TextBlock TextWrapping="Wrap" Padding="5" Foreground="White" Panel.ZIndex="7" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="15,-110,-43,0" Width="198" Height="122">
            <TextBlock.Effect>
                <DropShadowEffect BlurRadius="4" Direction="0" ShadowDepth="0" />
            </TextBlock.Effect>
                    <outlineText:OutlinedTextBlock Height="146" Width="192" TextOptions.TextRenderingMode="Aliased" FontFamily="Segoe UI" FontSize="100" x:FieldModifier="public" x:Name="middleForcastCurrentTemp" 
                                            FontWeight="Medium" TextWrapping="Wrap" TextAlignment="Right" Stroke="Black" StrokeThickness="3" Fill="White" Text="10"/>
        </TextBlock>
    </Grid>

And in my MainWindow code:

public MainWindow()
        {
            InitializeComponent();

            curTemp _curTempWindow = new curTemp();

            _curTempWindow._valTempChange = "55";

        }

When I run that code it never shows "55" in the textBlock. It only shows my default text "10".

What am I doing incorrect here?

Upvotes: 0

Views: 866

Answers (3)

mm8
mm8

Reputation: 169400

curTemp is not a window. It's a UserControl. Where do you create the instance of this UserControl that you actually see on the screen? Probably in your XAML markup, i.e. in MainWindow.xaml.

You could then give the element an x:Name in XAML:

<local:curTemp x:Name="uc" />

...and set the _valTempChange property of this instance using its name:

public MainWindow()
{
    InitializeComponent();
    uc._curTempWindow._valTempChange = "55";
}

Upvotes: 0

Justin CI
Justin CI

Reputation: 2741

You need to access the current object of the user control. Currently you are creating a new object. I am not sure how you are using the user control and what pattern you use.

You can create a singleton instance in user control and access the user control instance from Main Window.

Upvotes: 1

Fratyx
Fratyx

Reputation: 5797

You are creating a new instance of curTemp in the constructor of your MainWindow but you don't display it.

May it be that you create a curTemp instance in the XAML code of your MainWindow? Then you don't modify the text of this displayed curTemp instance but the text of the newly created (second) but not shown curTemp instance called _curTempWindow

Upvotes: 0

Related Questions