【问题标题】:Can I update the value of a WPF binding from the C# code behind?我可以从后面的 C# 代码更新 WPF 绑定的值吗?
【发布时间】:2011-12-02 16:15:16
【问题描述】:

我正在学习 C# 并构建一个 UI,用于将整数读取和写入 XML 配置文件。 UI 使用各种自定义用户控件。我有一个绑定到单个 int 变量的 3 单选按钮用户控件(控件返回 0、1、2)。控件使用事件来触发更新。它查看 3 个 isChecked 属性以确定新的 int 值。但是我不知道如何从后面的代码中更新原始绑定值。可以说它曾经被删除,因为有两个绑定..一个在主窗口中,一个在用户控件中。作为一个初学者,我在这一点上迷路了。顺便说一句,将 int 值读入 3 个单选按钮正在使用转换器。

这里是用户控件 xaml.cs...

namespace btsRV7config.controls
{
    public partial class ui3X : UserControl
    {
        public ui3X()
        {
            InitializeComponent();
        }

        void _event(object sender, RoutedEventArgs e)
        {
            int newValue = 0;
            if (rdbttn1.IsChecked == true) { newValue = 0; }
            else if (rdbttn2.IsChecked == true) { newValue = 1; }
            else if (rdbttn3.IsChecked == true) { newValue = 2; }
            txtb.Text = newValue.ToString(); //tempRemove

            // !!! assign newValue to Binding Source !!!
            //---------------------------------------------
            uiBinding1 = newValue;
            BindingOperations.GetBindingExpression(rdbttn1, RadioButton.IsCheckedProperty).UpdateSource();
            //---------------------------------------------
        }

        public static readonly DependencyProperty uiBinding1Property = DependencyProperty.Register("uiBinding1", typeof(int), typeof(ui3X));
        public int uiBinding1
        {
            get { return (int)GetValue(uiBinding1Property); }
            set { SetValue(uiBinding1Property, value); }
        }

        public static readonly DependencyProperty uiBinding2Property = DependencyProperty.Register("uiBinding2", typeof(int), typeof(ui3X));
        public int uiBinding2
        {
            get { return (int)GetValue(uiBinding2Property); }
            set { SetValue(uiBinding2Property, value); }
        }

        public static readonly DependencyProperty uiBinding3Property = DependencyProperty.Register("uiBinding3", typeof(int), typeof(ui3X));
        public int uiBinding3
        {
            get { return (int)GetValue(uiBinding3Property); }
            set { SetValue(uiBinding3Property, value); }
        }
    }
}

这里是用户控件 xaml

<UserControl x:Class="btsRV7config.controls.ui3X"
             x:Name="root"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel Orientation="Horizontal" Height="22">

        <RadioButton Name="rdbttn1" VerticalAlignment="Center" Margin="0 0 10 0"
                     IsChecked="{Binding ElementName=root, Path=uiBinding1}"
                     Click="_event" />

        <RadioButton Name="rdbttn2" VerticalAlignment="Center" Margin="0 0 10 0"
                     IsChecked="{Binding ElementName=root, Path=uiBinding2}"
                     Click="_event" />

        <RadioButton Name="rdbttn3" VerticalAlignment="Center"
                     IsChecked="{Binding ElementName=root, Path=uiBinding3}"
                     Click="_event" />

        <TextBox Name="txtb" Margin="5 0 0 0" Width="20" Height="17" /> <!-- tempRemove -->
    </StackPanel>
</UserControl>

这是 MainWindow.xaml 中使用的用户控件的示例

<Window x:Class="btsRV7config.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:controls="clr-namespace:btsRV7config.controls"
        xmlns:converter="clr-namespace:btsRV7config.converters"
        Title="Vans RV7 Configuration" Height="350" Width="525" >
    <Window.Resources>
        <converter:Int_Int_Bool_Converter x:Key="Int_Int_Bool" />
    </Window.Resources>

    <Grid>
        <controls:ui3X uiName="Font Color" ui1="Black" ui2="Green" ui3="Cyan"
                       uiBinding1="{Binding RV7sld_DFfontColor, Converter={StaticResource Int_Int_Bool}, ConverterParameter=0}"
                       uiBinding2="{Binding RV7sld_DFfontColor, Converter={StaticResource Int_Int_Bool}, ConverterParameter=1}"
                       uiBinding3="{Binding RV7sld_DFfontColor, Converter={StaticResource Int_Int_Bool}, ConverterParameter=2}" />
    </Grid>
</Window>

这里是 MainWindow.xaml.cs

namespace btsRV7config
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            record data = new record();
            DataContext = data;
        }
    }

    public class record : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private int _RV7sld_DFfontColor = RV7sld_dict["DFfontColor"];
        public int RV7sld_DFfontColor
        {
            get
            { return _RV7sld_DFfontColor; }
            set
            {
                _RV7sld_DFfontColor = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("RV7sld_DFfontColor"));
                }
            }
        }
    }
}

很抱歉发布这么多代码 - 我认为重要的是用户控件顶部的 xaml.cs。

这里是用户界面图片的链接。 我已经简化了我发布的代码以适应。 http://www.baytower.ca/photo/uiSample.jpg

所以 - '字体颜色'(RV7sld_DFfontColor) 可以是黑色(0) 绿色(1) 青色(2)

丹尼

【问题讨论】:

  • 您是否尝试在选中其他单选按钮时更新 Binding RV7sld_DFfontColor 的值?
  • 另外,对于您要完成的工作,我敦促您查看 RadioButton.GroupName 依赖属性。
  • 是的,我想在单击单选按钮时将“RV7sld_DFfontColor”值更新为“newValue”。 ...另外,我发现因为单选按钮在用户控件中,它们已经正确分组。当我分配一个组时,用户控件的每个实例都使用相同的组......所以没有它似乎工作正常。

标签: c# wpf binding user-controls code-behind


【解决方案1】:

BindingOperations 类使您能够“强制”任一方向的绑定更新。

假设后面的代码中有一个字符串属性X,XAML 中有一个TextBox,绑定到该属性:

// C#:
public string X { get; set; }

// XAML:
<TextBox Name="textBox1" Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=my:MainWindow, AncestorLevel=1}, Path=X}" />

要从textBox1.Text 复制到X,请执行以下操作:

BindingOperations.GetBindingExpression(textBox1, TextBox.TextProperty).UpdateSource();

要从X 复制到textBox1.Text,请执行以下操作:

BindingOperations.GetBindingExpression(textBox1, TextBox.TextProperty).UpdateTarget();

【讨论】:

  • 谢谢,我已更改分配 newValue 部分以符合您的建议。它还没有工作 - 但我会继续努力。
  • 有效!因为 WPF 控件位于自定义用户控件中,所以有两个绑定 - 一个在 MainWindow.xaml 中,一个在 ui3X.xaml 控件中。还有一个转换器可以测试 int 值以生成单选按钮的布尔值。一旦我将转换器从 mainWindow 移动到用户控件,它就可以工作了。我将更新上面的代码以反映更改。谢谢:)
  • 感谢您的提示!它允许我避免仅仅为了更新单个绑定而实现 INotifyPropertyChanged。
猜你喜欢
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 2010-12-31
  • 1970-01-01
相关资源
最近更新 更多