【问题标题】:Can I have one wpf control bind to two sources?我可以将一个 wpf 控件绑定到两个源吗?
【发布时间】:2013-05-27 11:20:21
【问题描述】:

基本上我有两个文本框,它们绑定到ListView 的两列。当用户在ListView 中选择一行时,值将显示在文本框中。这个没问题。

用户可以编辑一个TextBox 的文本,另一个TextBox 不可编辑。第二个TextBox 的文本是基于第一个TextBox 的文本。例如,第一个框是人民币的产品价格,第二个框是英镑的产品价格。汇率来自设置。用户只能编辑人民币的价值,不能编辑英镑。售价最初来自数据库。

我的目的是当用户更改第一个 TextBox 时,然后在 text_changed 事件中,我计算第二个 TextBox 的值。

当最终用户将选择更改为ListView 时,在我看来,与 GoodsSoldPriceCN 的绑定首先发生,然后触发了 text_changed 事件。在事件处理程序中,我计算第二个TextBox 的售价(以英镑为单位),这个双向绑定将更新源。问题是这不会更新用户刚刚选择的行,而是更新用户之前选择的行。

所以,我的问题是我怎样才能达到这个要求。

两个文本框绑定到ListView 中的一行选择。 当用户手动更改第一个 TextBox 的文本时,第二个文本框也会绑定到第一个框的文本。

我的代码如下:

XAML

<TextBox Grid.Row="2" Grid.Column="1" HorizontalAlignment="Stretch" Name="GoodsSoldPriceCN" Style="{StaticResource textBoxInError}" TextChanged="GoodsSoldPriceCN_TextChanged">
    <TextBox.Text>
        <Binding Path="soldpricecn" ConverterCulture="zh-cn">
            <Binding.ValidationRules>
                <ValidationRules:MoneyValueRule Min="1" Max="100000"></ValidationRules:MoneyValueRule>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>                 

<TextBox Grid.Row="3" Grid.Column="1" HorizontalAlignment="Stretch" Name="GoodsSoldPriceGB" IsEnabled="False"  Style="{StaticResource textBoxInError}" Text="{Binding Path=soldpricegb, Converter={StaticResource MoneyValueConverter}, UpdateSourceTrigger=PropertyChanged, ConverterCulture=en-gb}" />

Code

private void GoodsSoldPriceCN_TextChanged(object sender, TextChangedEventArgs e)
{
    isDirtyOrder = true;
    ListViewItem item = e.OriginalSource as ListViewItem;

    try
    {
        if (!String.IsNullOrEmpty(GoodsSoldPriceCN.Text))
            GoodsSoldPriceGB.Text =
            (decimal.Parse(GoodsSoldPriceCN.Text) / decimal.Parse (Properties.Settings.Default.ExchangeRate)).ToString();
        }

        catch (Exception ex)
        {                
            MessageBox.Show(ex.ToString());
        }          
    }
 ...
}      

【问题讨论】:

  • 您可以通过创建附加属性来实现。
  • 你能告诉我更多细节吗?在哪个类中创建附加属性?

标签: wpf binding


【解决方案1】:

我使用 Binding.SourceUpdated 事件而不是 TextChanged 事件来解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多