簡體   English   中英

彈出文本框TwoWay綁定

[英]Flyout Textbox TwoWay Binding

我試圖在彈出框中設置我的文本框文本綁定,但我的viewmodel的綁定屬性的setter永遠不會被調用。 我有這樣的視圖設置:

<CommandBar>
   <AppBarButton Icon="Edit" AllowFocusOnInteraction="true">
      <Flyout>
         <StackPanel>
            <TextBlock Text="Enter Qty:" />
            <TextBox Text="{Binding EditQty, Mode=TwoWay}" InputScope="Number" />
            <Button Content="Update" Command="{Binding EditCommand}" />
         </StackPanel>
      </Flyout>
<CommandBar>

我的viewmodel代碼也很簡單:

public decimal _editQty;
public decimal EditQty
{
    get => _editQty;
    set => Set(ref _editQty, value);
}

我甚至嘗試使用UpdateSourceTrigger = Explicit和綁定,然后在按鈕的click事件中,設置codebehind來調用

textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();

在調試過程中,我可以看到textBox.Text值已正確更改,但UpdateSource()仍未調用setter。 如果重要的話,我正在使用Windows 10 Build 14393(周年紀念版)。

有沒有辦法做到這一點? 在這一點上,我將不得不廢棄這個想法並將文本框放在一個對話框中,即使它在彈出窗口中有更好的用戶體驗。

根據微軟的說法,自WinRT天以來,UWP無法對小數進行TwoWay綁定! (原因是:不要問!)他們的解決方案是使用浮動。

如果你真的需要綁定到十進制,似乎你可以使用IValueConveter手動轉換(感謝Stephan Olson,其解決方案與答案相關聯):

public class DecimalConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value.ToString();
    }
    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return decimal.Parse(value as string);
    }
}

我的綁定現在看起來像這樣:

<TextBox Text="{Binding EditQty, Mode=TwoWay, Converter={StaticResource DecimalConverter}}" InputScope="Number" />

有時,在處理具有備用可視樹的彈出窗口/控件時會發生這種情況。 有些屬性不會級聯。 每當發生這種情況時,我使用TextBlock來打印DataContext的類型:

<CommandBar>
   <AppBarButton Icon="Edit" AllowFocusOnInteraction="true">
      <Flyout>
         <StackPanel>
            <TextBlock Text="{Binding}" /> <!-- This will print typeof DataContext -->

            <TextBlock Text="Enter Qty:" />
            <TextBox Text="{Binding EditQty, Mode=TwoWay}" InputScope="Number" />
            <Button Content="Update" Command="{Binding EditCommand}" />
         </StackPanel>
      </Flyout>
<CommandBar>

如果TextBlock打印為空,那么您就知道DataContext沒有將其記錄到您的Flyout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM