Question

I have a RootViewModel class, and I want to access an UI element (instantialized in MainWindow) from there. For that I set the class this way:

 class RootViewModel : MainWindow, INotifyPropertyChanged

But the application doesn't start. It compiles and throws no error but the Window doesn't appear. If I remove that MainWindow, I can't access my element that has been created in MainWindow.xaml. What can I do to solve this?

EDIT: Ok, I understand that I shouldn't be doing that, it's going against what it is MVVM. But is there a way to modify directly something from MainWindow? What should I try instead of this?

Was it helpful?

Solution 3

I was able to achieve what I wanted by creating a

public ObservableCollection<ChartPlotter> myPlotCollection { get; set; }

And then adding a ChartPlotter there, and setting in XAML:

 <DockPanel Grid.Column="2">
        <ItemsControl  Width="Auto" 
                   Height="Auto"
                   ItemsSource="{Binding myPlotCollection}">
        </ItemsControl>

    </DockPanel>

So this way I have complete control over what is happening in myPlotCollection[0]. At this moment it's enough for me, later I'll give it another try to bind it properly.

OTHER TIPS

Consider changing RootViewModel to a UserControl. Give it a DependencyProperty called Element, of type UIElement.

Add RootViewModel to the XAML for MainWindow and bind to the element you want to use, like this;

<RootViewModel Element="{Binding ElementName=SourceElement}"/>

WPF windows are objects, so you can always instantiate them manually, like so:

var foo = new FooWindow(); // new Window object
foo.Show(); // show window as non-blocking "dialog"

If you do that, you have access to any public or protected members of the window - that includes any child controls, as long as their Accessibility properties are marked accordingly. So, if FooWindow had a TextBox named txtFooName, you could access it like so:

string name = foo.txtFooName.Text // get string value from textbox

You can also assign to any public/protected members:

foo.txtFooName.Text = "Fizz Buzz, Inc.";

Now, MainWindow is generally set as the StartupUri of the application (in App.xaml), which makes it the entry point for the application, so I'm not entirely sure what you're trying to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top