x:Static in UWP XAML

后端 未结 4 1083
无人共我
无人共我 2020-12-08 20:09

An app I\'m working on requires a ConverterParameter to be an enum. For this, the regular way to do would be:

{Binding whatever, 
    Converter={StaticResour         


        
相关标签:
4条回答
  • 2020-12-08 20:29

    This works for me in a UWP:

    <Button Command="{Binding CheckWeatherCommand}">
      <Button.CommandParameter>
         <local:WeatherEnum>Cold</local:WeatherEnum>
      <Button.CommandParameter>
    </Button>
    
    0 讨论(0)
  • 2020-12-08 20:30

    This is an answer utilizing resources and without Converters:

    View:

    <Page
    .....
    xmlns:local="using:EnumNamespace"
    .....
    >
      <Grid>
        <Grid.Resources>
            <local:EnumType x:Key="EnumNamedConstantKey">EnumNamedConstant</local:SettingsCats>
        </Grid.Resources>
    
        <Button Content="DoSomething" Command="{Binding DoSomethingCommand}" CommandParameter="{StaticResource EnumNamedConstantKey}" />
      </Grid>
    </Page>
    

    ViewModel

        public RelayCommand<EnumType> DoSomethingCommand { get; }
    
        public SomeViewModel()
        {
            DoSomethingCommand = new RelayCommand<EnumType>(DoSomethingCommandAction);
        }
    
        private void DoSomethingCommandAction(EnumType _enumNameConstant)
        {
         // Logic
         .........................
        }
    
    0 讨论(0)
  • 2020-12-08 20:39

    There is no Static Markup Extension on UWP (and WinRT platform too).

    One of the possible solutions is to create class with enum values as properties and store instance of this class in the ResourceDictionary.

    Example:

    public enum Weather
    {
        Cold,
        Hot
    }
    

    Here is our class with enum values:

    public class WeatherEnumValues
    {
        public static Weather Cold
        {
            get
            {
                return Weather.Cold;
            }
        }
    
        public static Weather Hot
        {
            get
            {
                return Weather.Hot;
            }
        }
    }
    

    In your ResourceDictionary:

    <local:WeatherEnumValues x:Key="WeatherEnumValues" />
    

    And here we are:

    "{Binding whatever, Converter={StaticResource converterName},
     ConverterParameter={Binding Hot, Source={StaticResource WeatherEnumValues}}}" />
    
    0 讨论(0)
  • 2020-12-08 20:54

    The most concise way I know of...

    public enum WeatherEnum
    {
        Cold,
        Hot
    }
    

    Define the enum value in XAML:

    <local:WeatherEnum x:Key="WeatherEnumValueCold">Cold</local:WeatherEnum>
    

    And simply use it:

    "{Binding whatever, Converter={StaticResource converterName},
     ConverterParameter={StaticResource WeatherEnumValueCold}}"
    
    0 讨论(0)
提交回复
热议问题