动态地GoToState返回false

本文关键字:false 返回 GoToState 动态 | 更新日期: 2023-09-27 18:03:53

我用Visual Studio 2012创建了最简单的WPF/c#应用程序。我想创建一个接口来编辑一个sqlite表(1和0值)。要做到这一点,应用程序在WrapPanel上生成一些ToggleButton,这个按钮应该被选中并处于State Selected状态。但是GoToState在每次togglebutton生成时返回false,而GoToState在btn。单击工作。

foreach (DataRow dr in ds_Macrolist_C.Tables[0].Rows)
{
    System.Windows.Controls.Primitives.ToggleButton btn3 = new System.Windows.Controls.Primitives.ToggleButton();
    btn3.Template = (ControlTemplate)System.Windows.Application.Current.FindResource("Template_8");
    p_zone.Children.Add(btn3);
    var states = VisualStateManager.GetVisualStateGroups(this);
    bool shouldReturnTrue = VisualStateManager.GoToElementState(this, "Selected", true);
    btn3.Click += (s, ee) =>
    {
        if (btn3.IsChecked == true)
        {
            bool success2 = VisualStateManager.GoToState(btn3, "UnSelected", true);
            //rest of code
        }
    };

WPF模板:

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="SelectGroupe">
        <VisualState x:Name="UnSelected"/>
        <VisualState x:Name="Selected">
            <Storyboard>
                <ColorAnimationUsingKeyFrames 
                    Duration="0:0:0.001" Storyboard.TargetName="grid" 
                    Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)">
                    <EasingColorKeyFrame Value="#FFC80008"/>
                </ColorAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
    </VisualStateGroup>

什么是错的,我怎么能解决它?

动态地GoToState返回false

首先,尝试将错误行更改为:

bool shouldReturnTrue = VisualStateManager.GoToState(btn3, "Selected", true);

您使用this而不是传递ToggleButton,我想说GoToState是这里调用的正确方法。

无论如何,很可能这不会工作。要做到这一点,你需要这个控件有一个带有工作的VisualStateManager的ControlTemplate。在您的代码中,您刚刚添加了ControlTemplate,但是控件仍然没有加载或呈现,包括它的VisualStateManager。

如果你这样做会发生什么?

foreach (DataRow dr in ds_Macrolist_C.Tables[0].Rows)
{
    System.Windows.Controls.Primitives.ToggleButton btn3 = new System.Windows.Controls.Primitives.ToggleButton();
    btn3.Template = (ControlTemplate)System.Windows.Application.Current.FindResource("Template_8");
    p_zone.Children.Add(btn3);
    var states = VisualStateManager.GetVisualStateGroups(this);
    btn3.Loaded += Button_Loaded;
    btn3.Click += (s, ee) =>
    {
        if (btn3.IsChecked == true)
        {
            bool success2 = VisualStateManager.GoToState(btn3, "UnSelected", true);
            //rest of code
        }
    };
}
private void Button_Loaded(object sender, EventArgs e)
{
    var button = sender as System.Windows.Controls.Primitives.ToggleButton;
    button.Loaded -= Button_Loaded;
    bool shouldReturnTrue = VisualStateManager.GoToState(button, "Selected", true);
}