Question

i create a dependency property to close a view from view model,

dependencyProperty:

  public static class WindowBehaviors 
  {      
     public static readonly DependencyProperty IsOpenProperty =
              DependencyProperty.RegisterAttached("IsOpen"
             , typeof(bool),
             typeof(WindowBehaviors),
             new UIPropertyMetadata(false, IsOpenChanged));

    private static void IsOpenChanged(DependencyObject   obj,DependencyPropertyChangedEventArgs args)
    {
        Window window = Window.GetWindow(obj);

        if (window != null && ((bool)args.NewValue))
            window.Close();
    }


    public static bool GetIsOpen(Window target)
    {
        return (bool)target.GetValue(IsOpenProperty);
    }

    public static void SetIsOpen(Window target, bool value)
    {
        target.SetValue(IsOpenProperty, value);
    }
}

and use it in my xaml like this:

<window
...
Command:WindowBehaviors.IsOpen="True">

it work's fine,but when i want to bind it to a property in viewModel,it dosen't work,and i guess,it dosen't work because i define the resource later in xaml.

in xaml:

 <Window.Resources>
     <VVM:myVieModel x:Key="myVieModel"/>
 </Window.Resources>

and i don't know what should i do,where should i put this:

Command:WindowBehaviors.IsOpen="{binding Isopen}"
Was it helpful?

Solution 3

Thanks for your helps,i fixed it and here is my solution, i used to use MVVMToolkit but now i'm useing MVVMlight and as you know in MVVMLight,we just define Application Resources Once in App.xaml.so we can bind all the window's properties simply,hope this can help some people who has the same problem!!

app.xaml

  <Application.Resources>
    <!--Global View Model Locator-->
    <vm:ViewModelLocator x:Key="Locator"
                         d:IsDataSource="True" />
  </Application.Resources>

and in the window(view)

DataContext="{Binding DefaultSpecItemVM, Source={StaticResource Locator}}"

and it works perfect.:D

OTHER TIPS

    public MainWindow()
            {
                InitializeComponent();

// DO THIS
                this.DataContext = Resources["myVieModel"];

            }

You need to bind the data context for the scope where your binding is in. Usually this is fairly high up in your XAML, usually the first element in your form or control.

In your case, the data context beeing a static resource the folllowing should work:

<grid DataContext="{StaticResource myVieModel}">
    <!-- the code with the binding goß into here -->
</grid>

Actually this is the same as ebattulga suggests, just the XAML way (no code behind).

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