2017-09-06 12 views
0

我有我的XAML頁面上的開關和一個標籤:如何通過綁定ViewModel鏈接開關和可視屬性?

<Switch x:Name="CpSwitch" Toggled="CpSwitch" /> 

<ViewCell x:Name="aBtn" Tapped="openPicker"> 
    <Grid VerticalOptions="CenterAndExpand" Padding="20, 0"> 
     <Label Text="Don't Know" /> 
     <Picker x:Name="aBtnPicker" SelectedIndexChanged="aBtnPickerSelectedIndexChanged" ItemsSource="{Binding Points}"> 
     </Picker> 
     <Label Text="{Binding ABtnLabel}"/> 
    </Grid> 
</ViewCell> 

我的視圖模型

public class SettingsViewModel: ObservableProperty 
{ 
    public SettingsViewModel() 
    { 
    } 

我想要做的是使用視圖模型,並在該視圖模型有切換狀態或者使ViewCell可見或不可見。

有人可以給我一些建議,關於如何使用ViewModel綁定ViewCell的開關和visible屬性。

回答

1

基本上你將它們綁定到你的視圖模型中相同的Boolean變量。

<Switch IsToggled="{Binding ShowViewCell}" /> 

<ViewCell IsVisible="{Binding ShowViewCell}"> 
    ... 
</ViewCell> 

並在您的視圖模型:

public class SettingsViewModel 
{ 
    public bool ShowViewCell {get;set;} 
} 

這保證了當開關接通的ViewCell變得可見。如果你想達到相反的,你可以寫一個自定義轉換器:

public class InverseBoolConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return !(bool)value; 
    } 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return !(bool)value; 
    } 
} 

它添加到您的App.xaml資源字典:

<Application.Resources> 
    <ResourceDictionary> 
     <converters:InverseBoolConverter x:Key="InverseBoolConverter" /> 
    </ResourceDictionary> 
</Application.Resources> 

並應用到ViewCell:

<Switch IsToggled="{Binding ShowViewCell, Converter={StaticResource InverseBoolConverter}}" /> 
+0

難道你不只是在視圖模型的構造函數中添加一個'ShowViewCell = true'? – Harry

+0

布爾的默認值爲false,所以絕對推薦設置它。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/default-values-table 可以這樣做這雖然 公共BOOL ShowViewCell {獲得;組; } = true; – Joagwa

相關問題