gpt4 book ai didi

c# - WPF UserControl 无法在窗体外部绑定(bind)

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:41 25 4
gpt4 key购买 nike

我已经在它自己内部绑定(bind)了它,但我无法弄清楚表单绑定(bind)有什么问题。我正在检查不同的帖子,但我仍然无法得到它(

用户控制 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();
}
}

我对数据上下文的看法:

{
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) 如果您想从控件外部绑定(bind)到 UserControl,则永远不要将 DataContext 设置为其自身。从 UserControl 声明中删除:DataContext="{Binding RelativeSource={RelativeSource Self}}"

b) 使用 UserControl 内部的 RelativeSource Binding 将数据绑定(bind)到它自己的属性:

<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>

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

c) 正确定义您的 DependencyProperty(示例取自 MSDN 上的 Custom Dependency Properties 页面):

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 属性的名称将数据绑定(bind)到...在这种情况下,上面的代码将变为:

<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" />

关于c# - WPF UserControl 无法在窗体外部绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34008589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com