简体   繁体   中英

Is it possible to use System.Windows.Visibility in a portable class library targeting Windows Phone 8 and .NET for Windows Store?

I'm writing a Windows Phone 8 app, using the MVVM pattern, and I'm trying to do something as simple as putting my ViewModel into a portable class library (PCL) so that I can reuse the ViewModel in the event I write a tablet or PC version of the app.

That said, I'm trying to bind some of my controls' "Visibility" attribute to a viewmodel property like so...

using System.Windows;

public class MyViewModel
{

private bool shouldShowButton1;

public Visibility Button1_Visibility
{
   get
   {
     return shouldShowButton1 ? Visibility.Visible : Visibility.Collapsed;
   }
}
}

Lo and behold, I am greeted with the following error:

"The name 'Visibility' does not exist in the current context."

Is there any way to defeat this?

Nope. Besides, this shouldn't exist in your VM anyhow.

Simply have a boolean indicator of some state within the view model (note, I said state rather than an indication that a button should be visible):

public bool ShoppingCartIsValid { get { /*snip*/ } set { /*INotifyPropertyChanged*/ }

In your UI, you would bind the button's visibility to this property using the BooleanToVisibilityConverter to convert the bool to Visibility :

<Window.Resources>
  <BooleanToVisibilityConverter
         x:Key="btvc"  />
</Window.Resources>

Or whatever the root of your UI is in your particular app, and then

<Button Visibility="{Binding ShoppingCartIsValid, 
                          Converter={StaticResource btvc}}" />

Now, I'm not sure if the type exists within the WP8 API or for windows store applications (I haven't made any apps yet), but if not it is simply trivial to create such a converter using the IValueConverter interface. Examples can be found here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM