wpf - 是否可以在不设置 DataContext 的情况下绑定(bind)代码隐藏属性?

标签 wpf xaml

如题,
我看到几个类似的问题thisthis在 SO 中,但我没有看到解决方案。

我知道如果我需要绑定(bind)到code-beind,我需要设置Datacontext = this
但我的问题是我的数据上下文已经绑定(bind)到我的 ViewModel,但我想使用代码隐藏中定义的命令进行一些 UI 操作。

是否可以在 xaml 中绑定(bind)它?如果是这样,怎么做?

编辑:我确实尝试了以下方法:

<Window x:Class="WpfApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" x:Name="_Root">
<Grid x:Name="hellogrid">
    <TextBlock x:Name="myTextBlock" Text="AAAA"/>
    <Button Margin="82,119,121,120" Name="button2" Content="{Binding Path=Text, ElementName=myTextBlock}"/>
    <Button Margin="82,72,121,0" Name="button3" Content="{Binding Path=MyText, ElementName=_Root}" Height="23" VerticalAlignment="Top" />
</Grid>

和代码隐藏:
public partial class Window1 : Window
{
    public string MyText { get; set; }

    public Window1()
    {
        InitializeComponent();
        MyText = "ABC";
    }
}

我可以看到 Button2 显示 AAAA ,但 Button3 什么也没显示....

最佳答案

当然

有许多类型的绑定(bind)。最基本的绑定(bind)到 DataContext 上的属性。 ,通常继承自 Parent 对象

<DataTemplate DataType="{x:Type MyModel}">
    <!-- DataContext is object of type MyModel -->
    <local:MyView />
</DataTemplate>

或者
<Window x:Name="MyWindow">
    <!-- DataContext Inherited from Window -->
    <TextBlock Text="{Binding SomeProperty}" /> 
</Window>

在哪里

var SomeObject = new SomeModel();
SomeObject.SomeProperty = "Test";
myWindow.DataContext = SomeObject;

其他绑定(bind)类型包括 ElementName ,您可以在其中指定要用作绑定(bind)数据源的目标 UI 元素
<StackPanel>
    <CheckBox x:Name="SomeCheckBox" />
    <TextBlock Text="{Binding ElementName=SomeCheckBox, Path=IsChecked}" />
</StackPanel>

或者
<local:MyUserControl x:Name="SomeUserControl">
    <Button Command="{Binding ElementName=SomeUserControl, Path=DataContext.SaveCommand}" />
</local:MyUserControl >

RelativeSource ,它允许您找到与当前对象相关的对象以用作 DataSource
<Window Title="Test">
    <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=Title}" />
</Window>

或者
<local:MyUserControl>
    <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:MyUserControl}}, Path=DataContext.SaveCommand}" />
</local:MyUserControl >

TemplateBinding ,它绑定(bind)是到 RelativeSource 的快捷方式绑定(bind)到模板化对象的绑定(bind)
<Button Content="Test">
    <Button.Template>
        <ControlTemplate TargetType="{x:Type Button}">
            <TextBlock Text="{TemplateBinding Content}" />
        </ControlTemplate>
    </Button.Template>
</Button>

关于wpf - 是否可以在不设置 DataContext 的情况下绑定(bind)代码隐藏属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9297939/

相关文章:

c# - 将 GridView 选定项设置为无

wpf - 将集合绑定(bind)到 ItemsSource 时如何过滤集合?

c# - 合并 xps 文档使最后一个重复

c# - 从资源触发资源

c# - WinRT XAML 工具包可视化错误

wpf - 如何获取 WinUI 的可视化编辑器?

c# - 如何在后台线程中创建 WPF 控件?

c# - WPF 最上面的选项使全屏应用程序转义

c# - 是什么导致 Xamarin xaml 中出现此异常?

c# - 您如何根据登录状态/角色限制/控制用户可以访问的导航路线?