簡體   English   中英

綁定到ViewModel和CodeBehind中的屬性

[英]Binding to properties in both the ViewModel and CodeBehind

我敢肯定,這是一個荒謬可笑的問題,但是無論如何我都在問,因為我已經搜索了很多東西,或者不理解我所看到的解決方案,或者找不到我想要的答案。

我有一個MVVM應用程序。 我的XAML是在DataContext設置為VM的情況下設置的,其中從VM的屬性填充屏幕上的數據項。 我的CodeBehind不會擺弄數據,只會擺弄與屏幕有關的東西。

我現在想做的是將某些UI元素綁定到foo.xaml.cs(CodeBehind)文件中的屬性。 例如,我想指定FontSize綁定到CB中的屬性,以便在CB的WindowInitialized處理程序中,它可以檢測屏幕大小並更改將所有屏幕項目的FontSize =綁定到的一個變量。

我可以通過在VM中創建一個公共屬性,然后將CB中的值“注入”到VM中的方式來解決此錯誤。 我知道這是可行的,但這是獲得我想要的行為的一種round回方式,這一點也不簡單,而且我確信這是錯誤的處理方式。

我四處搜尋,並嘗試了以下操作:

    FontSize="{Binding RelativeSource={RelativeSource Self},Path="MyFontSize"

(其中“ MyFontSize”是一個公共int屬性)和我發現的各種其他示例,但沒有一個起作用。

因此,具體來說,如果我的CodeBehind類稱為NameChangeSetupMainWindow,並且這就是“ MyFontSize”屬性所在的位置,

public partial class NameChangeSetupMainWindow : Window
{
    private int m_fontSize = 14;
    public int MyFontSize
    {
        get { return m_fontSize; }
        set
        {
            if (m_fontSize != value))
            {
                m_fontSize = (value > 0) ? value : 10;
            }
        }
    }
    ...
    ... rest of the class...
    ...
}

VM被稱為NameChangeSetupViewModel ,這就是“真實”數據所在的位置,並且DataContext指向ala:

<Window.DataContext>
    <local:NameChangeSetupViewModel/>
</Window.DataContext>

XAML中僅將那些UI項(與UI相關的工具提示,字體大小等)綁定到CodeBehind中的變量而不是將其容納在VM中的語法是什么?

在此先感謝您提供的任何指導。

您可以使用RelativeSource AncestorType綁定到視圖本身的屬性:

<TextBlock FontSize="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=MyFontSize}" />

使用ElementName應該也可以工作:

<Window x:Name="window">

    <TextBlock FontSize="{Binding ElementName=window,Path=MyFontSize}" />
</Window>

編輯

這是我已經確認可以正常工作的示例:

XAML

<Window x:Class="WpfAbc.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    ToolTip="{Binding RelativeSource={RelativeSource Self},Path=MyToolTip}"
    >
    <Grid>
        <TextBlock Text="hello world" FontSize="{Binding RelativeSource={RelativeSource AncestorType=Window},Path=MyFontSize}" />
    </Grid>
</Window>

背后的代碼

public partial class MainWindow : Window
{
    private int m_fontSize = 20;
    public int MyFontSize
    {
        get { return m_fontSize; }
        set
        {
            if (m_fontSize != value)
            {
                m_fontSize = (value > 0) ? value : 10;
            }
        }
    }

    public string MyToolTip
    {
        get { return "hello world"; }
    }

    public MainWindow()
    {
        InitializeComponent();
    }
}

關於此主題的文章:

相關背景:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM