我的xaml代码:
<Grid>
<Interactivity:Interaction.Behaviors>
<Interactions:EventTriggerBehavior EventName="SizeChanged">
<Interactions:InvokeCommandAction Command="{Binding OnSizeChanged}"/>
</Interactions:EventTriggerBehavior
</Grid>
在ViewModel:
public IRelayCommand OnSizeChanged => new RelayCommand(SizeChangedEvent);
private void SizeChangedEvent()
{
// How to receive width and height at here
}
所以我的问题是如何接收与高度在视图模型?
感谢您可以使用CommandParameter
属性和值转换器。
XAML:
<Grid x:Name="grid">
<Interactivity:Interaction.Behaviors>
<Interactions:EventTriggerBehavior EventName="SizeChanged">
<Interactions:InvokeCommandAction Command="{Binding OnSizeChanged}">
<Interactions:InvokeCommandAction.CommandParameter>
<Binding ElementName="grid">
<Binding.Converter>
<local:SizeConverter />
</Binding.Converter>
</Binding>
</Interactions:InvokeCommandAction.CommandParameter>
</Interactions:InvokeCommandAction>
</Interactions:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</Grid>
转换器:
public class SizeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language) =>
value is FrameworkElement fe ? (fe.ActualWidth, fe.ActualHeight) : (double.NaN, double.NaN);
public object ConvertBack(object value, Type targetType, object parameter, string language) =>
throw new NotSupportedException();
}
视图模型:
public IRelayCommand OnSizeChanged => new RelayCommand<(double, double)>(SizeChangedEvent);
private void SizeChangedEvent((double width, double height) size)
{
//...
}
Canvas不能有sizechanged
事件,因为Canvas使用绝对定位作为其包含的子元素的布局技术。如文件
因为绝对定位没有考虑到应用程序窗口的大小,缩放,或其他用户选择的大小,使用一个容器元素,以适应不同的方向和屏幕设置,如网格或StackPanel,通常是比使用画布更好的选择。有关更多信息,请参见使用XAML定义布局。
编辑:(基于评论)
对于Grid,你可以像下面的例子一样直接将sizechanged
事件绑定到ViewModel中的eventandler上
Xaml
<Grid SizeChanged="{x:Bind viewModel.Grid_SizeChanged,Mode=OneWay}">
</Grid>
Xaml.cs
ViewModel viewModel { get; set; } = new ViewModel();
public MainPage()
{
this.InitializeComponent();
}
ViewModel.cs
public class ViewModel
{
public void Grid_SizeChanged(object sender, SizeChangedEventArgs e)
{
var height = (sender as Grid).ActualHeight;
}
}