簡體   English   中英

根據文本框動態更新WPF滑塊

[英]Update WPF Slider dynamically based on textbox

我正在編寫WPF應用程序,並且有一個綁定到文本框的滑塊,反之亦然。

我的問題是,當更改文本框的值時,必須在更新滑塊的值之前單擊文本框的外面。

我希望滑塊值在用戶在文本框中輸入文本時或在文本框中按下Enter鍵時更改。

這是我的代碼:

XAML:

<Slider Name="sldrConstructionCoreSupplierResin" Minimum="0" Maximum="10" Grid.Column="1" Grid.Row="1" IsSnapToTickEnabled="True"/>
    <TextBox Name="txtConstructionCoreSupplierResin" Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, Converter={StaticResource RoundingConverter}}" Grid.Column="2" Grid.Row="1"/>

背后的代碼:

public class RoundingConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                double dblValue = (double)value;
                return (int)dblValue;
            }
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                int ret = int.Parse(value.ToString());
                return ret;
            }
            return 0;
        }
    } 

默認情況下,當控件失去焦點時,綁定將更新。 這就是為什么當您從TextBox中單擊時才看到更改。 您可以使用Binding的UpdateSourceTrigger屬性更改此設置,如下所示:

<TextBox Text="{Binding Value,ElementName=mySlider,UpdateSourceTrigger=PropertyChanged}" />

現在,只要Text屬性發生更改,而不是失去焦點時,TextBox就會更新其源代碼。

BindingUpdateSourceTrigger屬性設置為PropertyChanged

<TextBox Text="{Binding ElementName=sldrConstructionCoreSupplierResin, Path=Value, UpdateSourceTrigger = "PropertyChanged" Converter={StaticResource RoundingConverter}}"/>

在這里查看更多

暫無
暫無

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

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