How to properly reference a class from XAML [closed]

自古美人都是妖i 提交于 2019-11-30 05:31:22

问题


OK, this is a super super noob question, one that I'm almost embarrassed to ask...

I want to reference a class in my XAML file. It's a DataTemplateSelector for selecting the right edit template for a DataGrid column.

Anyway, I've written the class into my code behind, added the local namespace to the top of top of the XAML, but when I try to reference the class from the XAML, it tells me the class does not exist in the local namespace. I must be missing something really really simple but I just can't understand it...

Here's my code.

XAML:

<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tk="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:CustomFields"
xmlns:col="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="CustomFields.MainWindow"
x:Name="Window"
Title="Define Custom Fields"
Width="425" Height="400" MinWidth="425" MinHeight="400">

<Window.Resources>
    <ResourceDictionary>
        <local:RangeValuesEditTemplateSelector>
            blah blah blah...
        </local:RangeValuesEditTemplateSelector>
    </ResourceDictionary>
</Window.Resources>

C#:

namespace CustomFields
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            // Insert code required on object creation below this point.
        }
    }

    public class RangeValuesEditTemplateSelector : DataTemplateSelector
    {
        public RangeValuesEditTemplateSelector(){

            MessageBox.Show("hello");
        }
    }   
}

Any ideas what I'm doing wrong? I thought this should be simple as 1-2-3...

Thanks!


回答1:


OK... it suddenly started working. Just had to rebuild.




回答2:


You can add a key so you can set the datacontext in the xaml instead behind code:

   <local:RangeValuesEditTemplateSelector x:key="RVETS">

Then for example set the outer grid's DataContext:

   <Grid DataContext={Binding Source = {StaticResource RVETS}} //Something like this I think

Then anything within that grid you can just bind directly to the property you set behind code. Not sure if this is useful or not, just thought I'd share :)



来源:https://stackoverflow.com/questions/2523908/how-to-properly-reference-a-class-from-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!