문제

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?

도움이 되었습니까?

해결책 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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top