I am just trying to find out if is there a way to define different image sources based on page orientation in XAML.
Like:
<Image>
<Orientation is landscape>
<Image.Source = "landscape.png" />
</Orientation>
<Orientation is not landscape>
<Image.Source = "notlandscape.png" />
</Orientation>
</Image>
You can set a property of your ViewModel in the code behind of your Page and bind to that using a DataTrigger .
You will need to override the OnSizeAllocated()
method for that:
Code behind
private SomeViewModel _viewModel = new SomeViewModel();
public SomePage()
{
InitializeComponent();
BindingContext = _viewModel;
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
_viewModel.IsPortrait = height > width;
}
ViewModel
[ObservableProperty]
private bool _isPortrait;
or
private bool _isPortrait;
public bool IsPortrait
{
get => _isPortrait;
set => SetField(ref _isPortrait, value);
}
XAML
<Image>
<Image.Triggers>
<DataTrigger
TargetType="Image"
Binding="{Binding IsPortrait}"
Value="True">
<Setter
Property="Source"
Value="image_portrait.png" />
</DataTrigger>
<DataTrigger
TargetType="Image"
Binding="{Binding IsPortrait}"
Value="False">
<Setter
Property="Source"
Value="image_landscape.png" />
</DataTrigger>
</Image.Trigger>
</Image>
An alternative would be to use Visual States .
I believe you are looking for Orientation state triggers .
<Style x:Key="OrientationStateTriggerImageStyle"
TargetType="Image">
<Setter Property="VisualStateManager.VisualStateGroups">
<VisualStateGroupList>
<VisualStateGroup>
<VisualState x:Name="Portrait">
<VisualState.StateTriggers>
<OrientationStateTrigger Orientation="Portrait" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Property="Source"
Value="notlandscape.png" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="Landscape">
<VisualState.StateTriggers>
<OrientationStateTrigger Orientation="Landscape" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Property="Source"
Value="landscape.png" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateGroupList>
</Setter>
</Style>
I don't know if you can use it outside of a style declaration like it is demonstrated, but this will indeed achieve your goal without having to add new properties.
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.