简体   繁体   English

我可以从后面的 C# 代码更新 WPF 绑定的值吗?

[英]Can I update the value of a WPF binding from the C# code behind?

I'm learning C# and building a UI that reads and writes integers to an XML config file.我正在学习 C# 并构建一个 UI 来读取和写入整数到 XML 配置文件。 The UI uses a variety of custom user controls. UI 使用各种自定义用户控件。 I have a 3 radiobutton user control that binds to a single int variable (control returns 0,1,2).我有一个绑定到单个 int 变量的 3 个单选按钮用户控件(控件返回 0,1,2)。 The control uses an event to trigger the update.该控件使用一个事件来触发更新。 It looks at the 3 isChecked properties to determine the new int value.它查看 3 个 isChecked 属性以确定新的 int 值。 But I don't know how to update the original binding value from the code behind.但是我不知道如何从后面的代码中更新原始绑定值。 It's once removed so to speak because there are two binds..one in the main window and one in the user control.可以这么说,它曾经被删除过,因为有两个绑定……一个在主窗口中,一个在用户控件中。 As a beginner am lost at this point.作为初学者,我迷失在这一点上。 BTW reading the int value into the 3 radiobuttons is working using a converter.顺便说一句,将 int 值读入 3 个单选按钮正在使用转换器。

here is the user control xaml.cs...这是用户控件 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); }
        }
    }
}

here is user control xaml这是用户控件 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>

here is an example of the user control used in MainWindow.xaml这是 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>

here is MainWindow.xaml.cs这是 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"));
                }
            }
        }
    }
}

Sorry for posting so much code - I think the important is the user controls xaml.cs at top.抱歉发布了这么多代码 - 我认为重要的是用户控制顶部的 xaml.cs。

here is a link to a picture of the UI.这是 UI 图片的链接。 I've simplified the code I've posted to fit.我已经简化了我发布的代码以适应。 http://www.baytower.ca/photo/uiSample.jpg http://www.baytower.ca/photo/uiSample.jpg

So - 'Font Color'(RV7sld_DFfontColor) can be black(0) green(1) cyan(2)所以 - 'Font Color'(RV7sld_DFfontColor) 可以是 black(0) green(1) cyan(2)

Danny丹尼

The BindingOperations class enables you to "force" the binding updates in either direction. BindingOperations类使您能够在任一方向“强制”绑定更新。

Let's say there is a string property X in the code behind and there is a TextBox in XAML, bound to that property:假设后面的代码中有一个字符串属性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}" />

To copy from textBox1.Text to X do the following:要从textBox1.Text复制到X请执行以下操作:

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

To copy from X to textBox1.Text do the following:要从X复制到textBox1.Text请执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM