动态GoToState返回false

时间:2015-07-21 14:30:57

标签: c# wpf

我使用Visual Studio 2012创建了最简单的WPF / c#应用程序。 我想创建一个编辑sqlite表的接口(带有1和0值)。为此,应用程序在WrapPanel上生成一些ToggleButton,应检查此状态并选择State Selected。 但GoToState在每个ToggleButtonon生成时返回false,而btn.Click上的GoToState可以生效。

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>

有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:0)

首先,尝试更改错误的行:

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

您使用的是this而不是传递ToggleButton,我说GoToState是在此处调用的正确方法。

无论如何,无论如何,这很有可能无法发挥作用。为此,您需要控件使ControlTemplate具有可用的VisualStateManager。在您的代码中,您刚刚添加了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);
}