1

I have a class that is a viewmodel (using Prism). It has an associated XAML view. When I do

this.Cursor

there isn't any Cursor property available. What must I do in order to access the cursor so I can change its icon?

4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

4

Since the Cursor is a UI-related property, you should set the cursor in the View, not the ViewModel. this.Cursor should work fine from the code-behind the View

If your Cursor is based on something in the ViewModel such as if it's loading data, then use a DataTrigger in your XAML to change the Cursor when something like an IsLoading property is set to true

<Style TargetType="{x:Type Window}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsLoading}" Value="True">
            <Setter Property="Cursor" Value="Wait" />
        </DataTrigger>
    </Style.Triggers>
</Style>
Rachel
  • 130,264
  • 66
  • 304
  • 490
  • I need the cursor to change while work is being done in a particular method. I don't have a property like IsLoading. I want to set the cursor at the beginning of this method and change back at the end. Is there some other way? Also, how well does this work since it is all on the main thread? – 4thSpace Jan 11 '12 at 18:11
  • @4thSpace If your method is in the `ViewModel` then it is a better idea to create an `IsLoading` property on the ViewModel and use the `DataTrigger`. ViewModels should not care about the UI, and that includes Cursors. – Rachel Jan 11 '12 at 18:18
  • @4thSpace And I'm not sure why you're concerned about threading. The only time this could be an issue is if you're doing your processing on a background thread. Then you'd have to remember to do things like updating your `IsLoading` property on the main thread, either before you start processing or by using the `Dispatcher`. – Rachel Jan 11 '12 at 18:19
  • I tried your XAML. I don't see that DataTrigger has "Property" so I used Binding. I get a build error: Cannot resolve the Style Property 'Cursor'. Do you have some idea on that? – 4thSpace Jan 11 '12 at 18:41
  • Ok, I have it compiling. I didn't have TargetType (but still need Binding and not Property). I'm not see any difference with the cursor. Maybe it is because things are happening too fast. Is there some efficient way to test this? – 4thSpace Jan 11 '12 at 18:47
  • @4thSpace Sorry, my syntax might not have been correct since I wasn't using a compiler. I would suggest downloading [Snoop](http://snoopwpf.codeplex.com/) and taking a look at what the `DataContext` is to make sure it's your ViewModel. You may have to use a `RelativeSource` or `ElementName` binding to bind the `IsLoading` property correctly. And to test it, I'd just set `IsLoading` to true and see if the cursor is the right value. – Rachel Jan 11 '12 at 18:57