2017-01-23 78 views
0

我怎麼設置的DataContext到,如果我想從一個類綁定屬性:綁定使用的DataContext

<Rectangle DataContext="Scaling" Height="{Binding VerticalSliderHeight}" Width="{Binding VerticalSliderHeight}"> 
    <Rectangle.Fill> 
    <ImageBrush ImageSource="/Assets/Images/fader.png"/> 
    </Rectangle.Fill> 
</Rectangle> 

類:建議

public static class Scaling 
{ 
    //Just For Slider Resource 
    public static float VerticalSliderHeight { get; set; } 
    public static float VerticalSliderWidth { get; set; } 
    // 
} 

答案是WPF

更多信息在xaml端:

<Page.Resources> 

    <Style TargetType="Slider"> 
     <Setter Property="Background" Value="{ThemeResource SystemControlForegroundBaseMediumLowBrush}" /> 
     <Setter Property="BorderThickness" Value="{ThemeResource SliderBorderThemeThickness}" /> 
     <Setter Property="Foreground" Value="{ThemeResource SystemControlHighlightAccentBrush}" /> 
     <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" /> 
     <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" /> 
     <Setter Property="ManipulationMode" Value="None" /> 
     <Setter Property="UseSystemFocusVisuals" Value="True" /> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Slider"> 
        <Grid Margin="{TemplateBinding Padding}"> 
         <Grid.Resources> 
          <Style TargetType="Thumb" x:Key="SliderThumbStyleVertical"> 
           <Setter Property="BorderThickness" Value="0" /> 
           <Setter Property="Background" Value="{ThemeResource SystemControlForegroundAccentBrush}" /> 
           <Setter Property="Template"> 
            <Setter.Value> 
             <ControlTemplate TargetType="Thumb"> 

              <Rectangle Height="60" Width="30"> 
               <Rectangle.Fill> 
                <ImageBrush ImageSource="/Assets/Images/fader.png" Stretch="Uniform"/> 
               </Rectangle.Fill> 
              </Rectangle> 

             </ControlTemplate> 
            </Setter.Value> 
           </Setter> 
          </Style> 
          <Style TargetType="Thumb" x:Key="SliderThumbStyleHorizontal"> 
           <Setter Property="BorderThickness" Value="0" /> 
           <Setter Property="Background" Value="{ThemeResource SystemControlForegroundAccentBrush}" /> 
           <Setter Property="Template"> 
            <Setter.Value> 
             <ControlTemplate TargetType="Thumb"> 

              <Rectangle x:Name="HorizontalThumbRect" Height="30" Width="60"> 
               <Rectangle.Fill> 
                <ImageBrush ImageSource="/Assets/Images/fader2.png" Stretch="Uniform"/> 
               </Rectangle.Fill> 
              </Rectangle> 

             </ControlTemplate> 
            </Setter.Value> 
           </Setter> 
          </Style> 
         </Grid.Resources> 
         <Grid.RowDefinitions> 
          <RowDefinition Height="Auto" /> 
          <RowDefinition Height="*" /> 
         </Grid.RowDefinitions> 
         <ContentPresenter x:Name="HeaderContentPresenter" 
        x:DeferLoadStrategy="Lazy" 
        Visibility="Collapsed" 
        Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}" 
        Margin="{ThemeResource SliderHeaderThemeMargin}" 
        Content="{TemplateBinding Header}" 
        ContentTemplate="{TemplateBinding HeaderTemplate}" 
        FontWeight="{ThemeResource SliderHeaderThemeFontWeight}" 
        TextWrapping="Wrap" /> 
         <Grid x:Name="SliderContainer" Background="Transparent" Grid.Row="1" Control.IsTemplateFocusTarget="True"> 
          <Grid x:Name="HorizontalTemplate" MinHeight="44"> 
           <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="Auto" /> 
            <ColumnDefinition Width="Auto" /> 
            <ColumnDefinition Width="*" /> 
           </Grid.ColumnDefinitions> 
           <Grid.RowDefinitions> 
            <RowDefinition Height="0" /> 
            <RowDefinition Height="Auto" /> 
            <RowDefinition Height="0" /> 
           </Grid.RowDefinitions> 
           <Rectangle x:Name="HorizontalTrackRect" 
        Fill="DimGray" 
        Height="{ThemeResource SliderTrackThemeHeight}" 
        Grid.Row="1" 
        Grid.ColumnSpan="3" /> 
        <Rectangle x:Name="HorizontalDecreaseRect" Fill="DimGray" Grid.Row="1" /> 
        <Thumb x:Name="HorizontalThumb" 
       Background="{ThemeResource SystemControlForegroundAccentBrush}" 
       Style="{StaticResource SliderThumbStyleHorizontal}" 
       DataContext="{TemplateBinding Value}" 
       Grid.Row="0" 
       Grid.RowSpan="3" 
       Grid.Column="1" 
       AutomationProperties.AccessibilityView="Raw" /> 
          </Grid> 
          <Grid x:Name="VerticalTemplate" MinWidth="44" Visibility="Collapsed"> 
           <Grid.RowDefinitions> 
            <RowDefinition Height="*" /> 
            <RowDefinition Height="Auto" /> 
            <RowDefinition Height="Auto" /> 
           </Grid.RowDefinitions> 
           <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="0" /> 
            <ColumnDefinition Width="Auto" /> 
            <ColumnDefinition Width="0" /> 
           </Grid.ColumnDefinitions> 
           <Rectangle x:Name="VerticalTrackRect" 
        Fill="DimGray" 
        Width="{ThemeResource SliderTrackThemeHeight}" 
        Grid.Column="1" 
        Grid.RowSpan="3" /> 
           <Rectangle x:Name="VerticalDecreaseRect" 
        Fill="DimGray" 
        Grid.Column="1" 
        Grid.Row="2" /> 

           <Thumb x:Name="VerticalThumb" 
       Background="{ThemeResource SystemControlForegroundAccentBrush}" 
       Style="{StaticResource SliderThumbStyleVertical}" 
       DataContext="{TemplateBinding Value}" 
       Grid.Row="1" 
       Grid.Column="0" 
       Grid.ColumnSpan="3" 
       AutomationProperties.AccessibilityView="Raw"/> 
          </Grid> 
         </Grid> 
        </Grid> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Page.Resources> 

因此,似乎綁定在頁面資源內遇到了麻煩。有任何想法嗎?

+0

這是uwp不是WPF – Brizzler

+0

你想設置* DataContext *爲靜態類或任何類?它必須在XAML中或可以在代碼中?一般來說,你可以通過代碼來完成它 - 直接設置,通過綁定或通過資源來完成。 – Romasz

+0

有點脫離主題,但爲什麼你使用舊的綁定?它們被x:Bind所取代。這是編譯的綁定。他們更快,消耗更少的內存,https://msdn.microsoft.com/en-us/windows/uwp/xaml-platform/x-bind-markup-extension –

回答

0

好吧,如果您是DataBindingMVVM概念的新手,可能會有些不知所措,所以請試着用開放的思維來圍繞它。我會盡力使其儘可能地直線前進。


有兩種方法,你可以去了解它,

  1. 綁定觀對代碼隱藏
  2. 或綁定查看一個簡單的模型(MVVM模式)

我會爲兩者提供答案,只是最初的部分是不同的,然後他們都有一個共同的功能。

爲視圖綁定到代碼隱藏

爲此,您需要將視圖綁定到它自己的代碼隱藏,讓視圖知道你正在使用的結合是在代碼隱藏做到這一點,在您<Page>標籤使用

DataContext = "{Binding RelativeSource={RelativeSource Self}}"

現在,你有你的View(.xaml)聽你codeBehind(.xaml.cs)

它綁定到視圖模型(的.cs)

對於這個創建項目並將其命名爲"ViewNameViewModel"下一個新的Class。現在轉到您的視圖,然後使用xmlns:ViewModels="yourNameSpace"<Page>標記中添加NameSpace請注意,Visual Studio會顯示您的智能感知,以便您可以簡單地從那裏選擇。此外,本地名稱空間已添加,因此如果您在本地名稱空間中有viewModel(即無子目錄),則可以跳過添加名稱空間。

現在你已經添加了命名空間,則需要設置視圖的DataContext,由<Page>標籤

<Page xmlns:ViewModels="using:MyTestApp.ViewModels"> 
<Page.DataContext> 
    <ViewModels:MainPageViewModel/> 
</Page.DataContext> 

現在你已經有了下添加下​​面的代碼做你查看的DataContext綁定在這兩種情況下,公共部分:


重構您class使用double性能HeightWidthdouble不要讓他們也static使他們提高NotifyPropertyChanged與使用INotifyPropertyChanged接口

public class Scaling :INotifyPropertyChanged 
{ 
    public double VerticalSliderHeight 
    { 
     get { return verticalSliderHeight; } 
     set 
     { 
      verticalSliderHeight = value;  
      NotifyPropertyChanged("VerticalSliderHeight"); 
     } 
    } 

    private double verticalSliderWidth; 
    public double VerticalSliderWidth 
    { 
     get { return verticalSliderWidth; } 
     set 
     { 
      verticalSliderWidth = value; 
      NotifyPropertyChanged("VerticalSliderWidth"); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    internal void NotifyPropertyChanged(String info) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(info)); 
     } 
    } 
} 

這方面的,只要在屬性的變化值,視圖更新自己的最新值。

在你.cs(代碼隱藏或視圖模型)添加屬性,也使您的.cs實施NotifyPropertyChanged和財產:

private Scaling mySliderData; 
    public Scaling MySliderData 
    { 
     get { return mySliderData; } 
     set 
     { 
      mySliderData = value; 
      NotifyPropertyChanged("MySliderData"); 
     } 
    } 

現在,這一切都完成後,只需綁定你的元素,象下面這樣:

<Rectangle Height="{Binding MySliderData.VerticalSliderHeight}" Width="{Binding MySliderData.VerticalSliderHeight}"> 
    <Rectangle.Fill> 
    <ImageBrush ImageSource="/Assets/Images/fader.png"/> 
    </Rectangle.Fill> 
</Rectangle> 

通過這種方式,您的代碼具有可擴展性,並且易於重構。我希望我解決了你的查詢,如果有什麼我會很樂意幫助評論部分

+0

謝謝,我'll試試看,並讓你知道:) – Brizzler

+0

我仍然收到此錯誤:錯誤:BindingExpression路徑錯誤:'Windows.Foundation.IReference'1''找不到'VerticalSliderWidth'屬性''。 BindingExpression:Path ='VerticalSliderWidth'DataItem ='Windows.Foundation.IReference'1 ';目標元素是'Windows.UI.Xaml.Shapes.Rectangle'(Name ='null');目標屬性是'寬度'(類型'Double') – Brizzler

+0

Brizzler