WPF UserControl不能在窗体外部绑定

马克西姆五世

我已经将它绑定在其内部,但是我无法弄清表单绑定的问题。我正在查看其他帖子,但仍然无法获取它(

用户控件XML:

<UserControl x:Class="Lab7_KPZ.Controls.UnitBar"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Lab7_KPZ.Controls"
             mc:Ignorable="d" 
             d:DesignHeight="177" d:DesignWidth="169" DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <Label x:Name="HPlabel" Content="{Binding _HP, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="0,131,0,0" VerticalAlignment="Top" Height="23" Width="169" Background="#FF35DC5B" HorizontalContentAlignment="Center"/>
        <Label x:Name="MPlabel" Content="{Binding _MP, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="0,154,0,0" VerticalAlignment="Top" Height="23" Width="169" Background="#FF0387E2" HorizontalContentAlignment="Center"/>

    </Grid>
</UserControl>

用户控件CS:

  public partial class UnitBar : UserControl, INotifyPropertyChanged
    {
        private string _hp = "1000 / 1000";
        private string _mp = "400 / 400";
        private string _imgPath;

        public string _HP
        {
            get
            { 
                return (string)GetValue(HitP);
            }
            set
            {

                SetValue(HitP, value);
                OnPropertyChanged("_HP");
            }
        }
        public string _MP
        {
            get
            {
                return _mp;
            }
            set
            {
                _hp = value;
                OnPropertyChanged("_MP");
            }
        } 

        public static readonly DependencyProperty HitP = DependencyProperty.Register("_HP", typeof(string), typeof(UnitBar),
                               new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, EmpNamePropertyChanged));
        static void EmpNamePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            UnitBar x = (UnitBar)sender;
            x._HP = (string)e.NewValue;
        }
        public UnitBar()
        {
            InitializeComponent();
           (this.Content as FrameworkElement).DataContext = this; 
        }

        public event PropertyChangedEventHandler PropertyChanged; 
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

主窗口xml:

<Window x:Class="Lab7_KPZ.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Lab7_KPZ"
        xmlns:controls="clr-namespace:Lab7_KPZ.Controls"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid Name="mainGrid"> 
        <controls:UnitBar _HP="{Binding Path=HP, UpdateSourceTrigger=PropertyChanged, Mode=OneWay }"> </controls:UnitBar> 

        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="10,237,0,0" TextWrapping="Wrap" Text="{Binding Path=HP, UpdateSourceTrigger=PropertyChanged, Mode=OneWay }" VerticalAlignment="Top" Width="52" />
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="10,192,0,0" VerticalAlignment="Top" Width="75" Command="{Binding  Path=SaveCommand, UpdateSourceTrigger=PropertyChanged}"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="205,20,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Text="{Binding Path=HP, UpdateSourceTrigger=PropertyChanged, Mode=OneWayToSource }"/>

    </Grid>
</Window>

main window cs:
  public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MyView(); 
        } 
    }

我对datacontext的看法:

{
        private string _hp;
        private int _mp;
        private int i = 5;

        public string HP
        {
            get { return _hp; }
            set
            {
                _hp = value;
                OnPropertyChanged("HP");
            }
        }
        public string stringHP
        {
            get { return "100 / 100"; } 
        }
        public int MP
        {
            get { return _mp; }
            set {
                _mp++;
                OnPropertyChanged("MP");
                }
        }

        private ICommand _saveCommand;

        public ICommand SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                {
                    _saveCommand = new RelayCommand(
                        param => this.SaveObject(),
                        param => this.CanSave()
                    );
                }
                return _saveCommand;
            }
        }

        private bool CanSave()
        {
            // Verify command can be executed here
            return true;
        } 
        private void SaveObject()
        {
            // Save command execution logic 
        } 


        public event PropertyChangedEventHandler PropertyChanged;

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
谢里登

您的代码有几个问题。

a)如果要从控件外部绑定到DataContexta UserControl,则永远不要将其设置为a UserControl声明中删除它DataContext="{Binding RelativeSource={RelativeSource Self}}"

b)使用RelativeSource Bindingfrom中的UserControlto数据绑定到其自身的属性:

<Grid>
    <Label x:Name="HPlabel" Content="{Binding _HP, RelativeSource={RelativeSource 
        AncestorType={local:UnitBar}}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
        HorizontalAlignment="Left" Margin="0,131,0,0" VerticalAlignment="Top" Height="23" 
        Width="169" Background="#FF35DC5B" HorizontalContentAlignment="Center" />
    <Label x:Name="MPlabel" Content="{Binding _MP, RelativeSource={RelativeSource 
        AncestorType={local:UnitBar}}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
        HorizontalAlignment="Left" Margin="0,154,0,0" VerticalAlignment="Top" Height="23" 
        Width="169" Background="#FF0387E2" HorizontalContentAlignment="Center" />
</Grid>

这将使您能够将数据UserControl从控件外部绑定到

c)DependencyProperty正确定义您的s(示例取自MSDN上的“自定义依赖项属性”页面):

public static readonly DependencyProperty AquariumGraphicProperty = DependencyProperty.Register(
  "AquariumGraphic",
  typeof(Uri),
  typeof(AquariumObject),
  new FrameworkPropertyMetadata(null,
      FrameworkPropertyMetadataOptions.AffectsRender, 
      new PropertyChangedCallback(OnUriChanged)
  )
);
public Uri AquariumGraphic
{
  get { return (Uri)GetValue(AquariumGraphicProperty); }
  set { SetValue(AquariumGraphicProperty, value); }
}

请注意命名约定... CLR属性获取常规属性名称,并且DependencyProperty获取相同名称,但在其末尾附加“ Property”。在这些属性之一的名称中使用下划线是非常罕见的。在您的情况下,您DependencyProperty其中一个看起来像这样:

public static readonly DependencyProperty HitProperty = DependencyProperty.Register(
  "Hit",
  typeof(string),
  typeof(UnitBar),
  new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, EmpNamePropertyChanged)
);
public string Hit
{
  get { return (string)GetValue(HitProperty); }
  set { SetValue(HitProperty, value); }
}

在XAML中,我们使用CLR属性的名称将数据绑定到...,在这种情况下,上面的代码将变为:

<Label x:Name="HPlabel" Content="{Binding Hit, RelativeSource={RelativeSource 
    AncestorType={local:UnitBar}}, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 
    HorizontalAlignment="Left" Margin="0,131,0,0" VerticalAlignment="Top" Height="23" 
    Width="169" Background="#FF35DC5B" HorizontalContentAlignment="Center" />

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

从窗体UserControl转换为WPF UserControl

来自分类Dev

在WPF / C#中具有绑定的外部UserControl

来自分类Dev

来自UserControl的WPF数据绑定

来自分类Dev

WPF UserControl上的TwoWay绑定

来自分类Dev

不接受UserControl中的WPF多重绑定

来自分类Dev

在ListView数据模板WPF中绑定UserControl

来自分类Dev

不接受UserControl中的WPF多重绑定

来自分类Dev

绑定wpf UserControl的代码隐藏属性

来自分类Dev

在WPF中将UserControl绑定到MainWindow元素

来自分类Dev

wpf UserControl 命令按钮单击绑定

来自分类Dev

将WPF窗口投射到WPF UserControl

来自分类Dev

将WPF窗口投射到WPF UserControl

来自分类Dev

WPF UserControl不显示

来自分类Dev

带ContextMenu wpf的UserControl

来自分类Dev

WPF的UserControl多个DataContexts?

来自分类Dev

symfony2:如何在窗体外部设置字段的值

来自分类Dev

绑定内绑定WPF

来自分类Dev

WPF绑定:如何在UserControl XAML中设置绑定源

来自分类Dev

WPF绑定:如何在UserControl XAML中设置绑定源

来自分类Dev

如何在WPF中绑定和刷新UserControl绑定?

来自分类Dev

WPF:在ListView的ObservableCollection外部进行绑定

来自分类Dev

WPF:在ListView的ObservableCollection外部进行绑定

来自分类Dev

WPF的DataGridComboBoxColumn绑定?

来自分类Dev

WPF ListBox绑定更新

来自分类Dev

WPF ComboBox绑定ItemsSource

来自分类Dev

WPF绑定桥

来自分类Dev

WPF按钮内容绑定

来自分类Dev

WPF与RelativeSource自身的绑定

来自分类Dev

WPF绑定用户娱乐