I have a relatively simple case where I want to repurpose a "Start" button with an "Abort" button after it is first clicked.
I'm wondering what is the best way to implement this button repurposing using XAML, hopefully declaratively rather than with a code-behind hack:
<DockPanel>
<Button x:Name="bt开发者_开发百科nStart">Start</Button>
</DockPanel>
I tried the following with using two distinct Button
s and toggling the Visibility
property of each but it does not reflow the layout within the DockPanel
. I want the buttons to share the same layout space but mutually exclusively. This also has the problem where only the last element fills the dock panel and the first element is squished off to the left.
<DockPanel>
<Button x:Name="btnStart">Start</Button>
<Button x:Name="btnAbort" Visibility="Hidden">Abort</Button>
</DockPanel>
I prefer the two Button
approach so that I can have separate Click
event handlers. Please don't suggest naive solutions like dynamically adding/removing Button elements. I'd prefer a declarative approach if at all possible. Thanks!
Did you try to set the Visibility
property to Collapsed
instead of Hidden
? If you do that, the unused button should not use any layout space.
If it's a viable option for you, you could try downloading the WPF toolkit and creating a single control with multiple states using the VisualStateManager.
Everything can be done declaratively in the XAML and switching between the States is fairly simple...especially if you're familiar at all with Silverlight development.
I don't mean to be snarky, but I wouldn't do it, unless you also change the visual state and look of the button to feel like something that would have that behavior, like an animated toggle switch or something. If the button launches a process which is slow running and you want to be able to abort it, I would think that (a) having a separate progress dialog showing the status and a cancellation option or (b) enabling that status and cancellation control in a different part of your window would be more consistent with other user interfaces. Also, accidental double clicks will immediately cancel the action, which might be odd.
When the button is clicked assign a different command to the button and change the caption. Then when it is clicked it will goto a completely different handler in the code behind.
精彩评论