我想在UWP应用程序中将按钮文本从"Run“更改为"Stop”并向后更改,并更改click flag的布尔属性。我尝试使用微软的XamlBehaviors库。
XAML:
<ToggleButton x:Name="ToggleButton" Grid.Row="1" Grid.Column="0"
Height="79" HorizontalAlignment="Stretch" Margin="33,0,-74,0"
IsChecked="{Binding IsGraphRenderingEnabled, Mode=TwoWay}"
Command="{Binding ToogleGraphRendering}">
<Grid>
<interactivity:Interaction.Behaviors>
<core:DataTriggerBehavior
Binding="{Binding IsChecked,
ElementName=ToggleButton}"
Value="True" />
<core:DataTriggerBehavior
Binding="{Binding IsChecked,
ElementName=ToggleButton}"
Value="False" />
<core:ChangePropertyAction TargetObject="{Binding GraphRenderingButtonText}"
PropertyName="Content"
Value="Run" />
</interactivity:Interaction.Behaviors>
</Grid>
</ToggleButton>
代码隐藏:
public MainViewModel()
{
InitializeCommands();
}
private bool _isGraphRenderingEnabled;
public bool IsGraphRenderingEnabled
{
get => _isGraphRenderingEnabled;
set => SetField(ref _isGraphRenderingEnabled, value);
}
private string _graphRenderingButtonText;
public string GraphRenderingButtonText
{
get => _graphRenderingButtonText;
private set => SetField(ref _graphRenderingButtonText, value);
}
private void InitializeCommands()
{
ToogleGraphRendering = new RelayCommand(StartStopRendering);
}
private async void StartStopRendering()
{
if (IsGraphRenderingEnabled)
{
GraphRenderingButtonText = "Stop";
var contentDialog = new ContentDialog
{
Title = "Attention!",
Content = "Are you sure to stop rendering?",
PrimaryButtonText = "ОК",
SecondaryButtonText = "Cancel"
};
await contentDialog.ShowAsync();
}
}
它不能正常工作。我无法更改按钮文本。所以我想我在Xaml行为上是错误的,但是我不知道在哪里…
发布于 2020-10-13 06:13:54
我会将以下代码添加到您的MainViewModel
类中:
public string RenderToggleText(bool? c)
=> c is bool check && check ? "Stop" : "Run";
并在XAML中定义ToggleButton
,如下所示:
<ToggleButton x:Name="ToggleButton" Grid.Row="1" Grid.Column="0"
Height="79" HorizontalAlignment="Stretch" Margin="33,0,-74,0"
IsChecked="{Binding IsGraphRenderingEnabled, Mode=TwoWay}"
Command="{Binding ToogleGraphRendering}"
Content="{x:Bind RenderToggleText(ToggleButton.IsChecked), Mode=OneWay}"/>
现在,当ToggleButton
的IsChecked
值更改时,将调用RenderToggleButton
方法,从而相应地更新其内容。
由于您似乎已经有了一个实现INotifyPropertyChanged
的GraphRenderingButtonText
属性,因此您也可以将ToggleButton
的Content
绑定到此属性:
Content="{x:Bind GraphRenderingButtonText, Mode=TwoWay}"
然而,在第一种方法中,您不再需要这个属性,因此您不必更改它,因为它是自动完成的。
https://stackoverflow.com/questions/64320258
复制相似问题