duykhoa
duykhoa

Reputation: 2302

Update a User Control from MainWindow

First, see this code in the MainWindow

    <Grid x:Name="LayoutRoot" MinWidth="900" MinHeight="650" RenderTransformOrigin="0.5,0.5">
        <local:RightSideContent x:Name="rightPanel"  Grid.Column="1"  Width="Auto" Height="Auto"/>

    </Grid>

I create a User Control name RightPanel and name it in MainWindow.xaml rightPanel

Example, in the User Control RightPanel has a TextBlock name textblock. Then, and I want to update the TextBlock and I am in MainWindow, I must call rightPanel.textblock.Text ="...".

So I think it is not a good way, because if I am in another Class, so I can't go back to MainWindow to update this textblock, and I can't call a method(static or non) to MainWindow or to RightPanel to update. Once more reason I think it isn't good, anytime you must interactive the MainWindow, instead I think we should send directly the message to RightPanel.

Please help me, thanks and forgive if my English isn't clear enough!

Upvotes: 2

Views: 382

Answers (2)

Thelonias
Thelonias

Reputation: 2935

You could create a Dependency Property called "Text" and then bind it to a property on the MainWindow's DataContext.

Assuming you're not following the MVVM pattern, you would have some property in your MainWindow.cs, the code-behind. For example:

private string _rightSideText = string.Empty;
public string RightSideText
{
    get { return _rightSideText; }
    set
    {
        _rightSideText = value;
        OnPropertyChanged("RightSideText");
    }
}

This assumes you've implemented INotifyPropertyChanged on your MainWindow.

Then, in your MainWindow XAML:

<Grid x:Name="LayoutRoot" MinWidth="900" MinHeight="650" RenderTransformOrigin="0.5,0.5">
    <local:RightSideContent Text="{Binding Path=RightSideText}" x:Name="rightPanel"  Grid.Column="1"  Width="Auto" Height="Auto"/>
</Grid>

This assumes you've added the dependency property.

Once that's done, all you need to do is set the "RightSideText" whenever you want to change the text.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564323

You can add a Dependency Property to your RightSideContent user control to handle the text. This would let you bind to it directly from your MainWindow's xaml.

The RightSideContent user control can then just bind the textblock.Text to that dependency property, displaying what's there.

Upvotes: 3

Related Questions