uwp - 如何从 UWP 中的视图模型访问用户控件?
问题描述
我有一个 UWP,其中我在 file1.xaml 中定义了一个用户控件
<UserControl>
<Grid x:Name="A">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="DemoStates">
<VisualState x:Name="State1"/>
<VisualState x:Name="State2">
<Storyboard
x:Name="StoryboardDemo"
FillBehavior="HoldEnd">
<DoubleAnimationUsingKeyFrames
EnableDependentAnimation="True"
Storyboard.TargetName="DemoStateChange"
Storyboard.TargetProperty="(SomeProperty)">
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid x:Name="StoryboardDemo">
<Image
Source="//assets//Image1.jpg"/>
<Image
Source="//assets//Image2.jpg"/>
</UserControl>
我在另一个 xaml 文件 file2.xaml 中使用这个用户控件
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<control:file1/>
<ToggleSwitch
Grid.Row="1"
Toggled="{x:Bind ViewModel.ChangeImage}"/>
</Grid>
如果用户在情节提要上切换切换开关应该进入状态2,如果它关闭它应该进入状态1。我试图通过视图模型控制这个情节提要
File2ViewModel.cs
public void ChangleImage(object sender, RoutedEventArgs e)
{
Windows.UI.Xaml.Controls.ToggleSwitch toggleSwitch = sender as Windows.UI.Xaml.Controls.ToggleSwitch;
if (toggleSwitch != null)
{
if (toggleSwitch.IsOn == true)
{
VisualStateManager.GoToState(file1 , "state2", false); //get an error for the first parameter
}
else
{
VisualStateManager.GoToState(file1, "state1", false);//get an error for the first parameter
}
}
如何触发用户控件从 ViewModel 启动情节提要?此外,如果切换开关我想发送一个值来操纵“someproperty”回用户控件,以便它可以基于它来操纵视图,是否有可能实现这一点?
解决方案
我误解了你的代码。您正在将其ChangleImage method
放入 ViewModel。您可以在 中设置一个属性File2ViewModel
并将控件分配给该属性。
我根据你的场景做了一个简单的演示
File2ViewModel:
public class File2ViewModel
{
public file1 thefile { get; set; }
public File2ViewModel(file1 file)
{
thefile = file;
}
public void ChangleImage(object sender, RoutedEventArgs e)
{
Windows.UI.Xaml.Controls.ToggleSwitch toggleSwitch = sender as Windows.UI.Xaml.Controls.ToggleSwitch;
if (toggleSwitch != null)
{
if (toggleSwitch.IsOn == true)
{
VisualStateManager.GoToState(thefile, "state2", false); //get an error for the first parameter
Debug.WriteLine("test");
}
else
{
VisualStateManager.GoToState(thefile, "state1", false);//get an error for the first parameter
Debug.WriteLine("test");
}
}
}
}
在后面的file2代码中:
public File2ViewModel viewModel { get; set; }
viewModel = new File2ViewModel(MyControl1);
MyControl1
是您添加到 file2 xaml 的 file1 控件。
推荐阅读
- python - 当将文件夹作为模块导入时如何生成 Spynx 文档?
- angular-cli - 如何使用 Angular cli 生成延迟加载模块
- c# - 通过构造函数传递泛型参数
- vba - Filesystemobject Textstream,在执行 Textstream.Close 时立即消失(正在创建.vbs 扩展名)
- node.js - 如何增加expressjs中的res时间
- python - Django,一页上两个不同加载文件的输出相同的文件
- javascript - 显示编号 导航栏上购物车中的项目在刷新时显示为 0
- c# - 部署时 Google App Engine 灵活 C# 连接到 Cloud SQL SQL Server 问题
- php - 超过 120 秒的最大执行时间
- json - xamarin 表单反序列化 json