【发布时间】:2016-03-21 23:28:13
【问题描述】:
我有一个附加行为,它使用CallMethodAction 行为在按下 ENTER 键时调用方法。 TextBox XAML 如下所示:
<TextBox x:Name="AddCategoryTextBox"
Width="180"
Text="{Binding Path=NewCategoryName,
Mode=TwoWay}"
Visibility="{Binding Path=AddCategoryVisible,
Converter={StaticResource BooleanToVisibilityConverter},
Mode=TwoWay}">
<interactivity:Interaction.Behaviors>
<behaviors:KeyBehavior Key="Enter">
<core:CallMethodAction MethodName="AddCategory" TargetObject="{Binding}" />
</behaviors:KeyBehavior>
</interactivity:Interaction.Behaviors>
</TextBox>
我知道该方法正在被调用,因为它还将AddCategoryVisible 更改为false,从而有效地隐藏了TextBox。这是AddCategory 方法:
public void AddCategory()
{
if (AddCategoryVisible)
{
// insert new category and set current invoice id
if (!string.IsNullOrEmpty(NewCategoryName))
{
var categoryId = InvoiceCategories.Count;
var category = new InvoiceCategory
{
CategoryName = NewCategoryName,
CategoryDescription = "",
CategoryId = categoryId
};
_invoiceCategoryRepository.InsertAsync(category);
InvoiceCategories.Add(category);
CurrentInvoice.CategoryId = categoryId;
NewCategoryName = string.Empty;
}
}
AddCategoryVisible = !AddCategoryVisible;
}
问题是当我按下 ENTER 键时,TextBox 会消失,但并不总是添加新类别。如果我再次返回添加新类别,输入的文本在那里,如果我再次点击ENTER,则成功。
我有一个Button,它在单击时调用完全相同的方法,并且它在 100% 的时间里都能正常工作。我不确定有什么区别,有什么我没有看到的吗?
该方法最初是async,而InsertAsync() 调用是awaited,但我暂时把它拿出来看看是否会有所不同。不幸的是,CallMethodAction 的行为仍然无法正常工作,但单击按钮后可以正常工作。这是Button 的 XAML:
<Button Command="{Binding Path=AddCategoryCommand}"
Content="+" />
还有AddCategoryCommand 定义:
public DelegateCommand AddCategoryCommand => new DelegateCommand(AddCategory);
如您所见,Button 只是调用与TextBox 相同的AddCategory 方法。
编辑
我认为还应该注意的是,我已尝试在方法中设置断点以确保一切正常。有了断点,该方法每次都能正确执行,所以在我看来这是某种时间问题,这就是我尝试删除 async 的原因。
【问题讨论】:
标签: c# xaml winrt-xaml attachedbehaviors