2013-04-29 8 views
1

Делаю заявку на МОФ C# в Expression Blend 4. Я следовал RumorMills учебника над на http://www.jarloo.com/rumormill4/Wpf C# тикер читатель Новостей

Однако он не обеспечивает полный учебник, поэтому я взял сом его кода, пытающегося внедрить его в мое приложение «домашний медиацентр» для тестирования. Я разобрал 90% ошибок, только один из них - я надеюсь, что у него не будет никаких дополнительных ... Вы можете найти любой дополнительный код, не включенный в вопрос, на свой пост. Смотрите мой код ниже:

Главный файл кода для экрана, на котором размещается новостная лента

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Shapes; 
using System.Windows.Media.Animation; 
using Microsoft.Expression.Controls; 
using MySoftware_Inspire.Feed; 
using System.ComponentModel; 
namespace blablabla 
{ 
/// <summary> 
/// Interaction logic for MainWindow.xaml 
/// </summary> 
public partial class MainWindow : Window 
{ 
    List<string> weatherwords = new List<string> {"weather", "in", "umbrella", "rain", "sun", "sunny", "overcast", "forecast", "cloudy"}; 
    List<string> mathwords = new List<string> {"+", "-", "*", "/", ":"}; 
    String searchInput; 
    System.Windows.Threading.DispatcherTimer dispatcherTimer; 

    private readonly FeedManager manager = new FeedManager(); 
    private readonly Ticker<TickerItem> ticker; 

    private delegate void FeedDelegate(FeedItem itm); 

    //would be better to detect the height of the titlebar 
    //and window chrome instead of hardcoding this. 
    private const int FULL_HEIGHT = 75; 
    private const int SHORT_HEIGHT = 55; 

    private int height = FULL_HEIGHT; 
    public MainWindow() 
    { 
     this.InitializeComponent(); 

     Width = SystemParameters.PrimaryScreenWidth; 

     ticker = new Ticker<TickerItem>(LayoutRoot) {Speed = new TimeSpan(0, 2, 0)}; 
     ticker.ItemDisplayed += ticker_ItemDisplayed; 

     manager.NewFeedItem += manager_NewFeedItem; 

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

      private void ticker_ItemDisplayed(object sender, ItemEventArgs<TickerItem> e) 
    { 
     txtItems.Text = ticker.Items.Count.ToString(); 

     manager.MarkFeedAsRead(e.Item.FeedItem); 
    } 

    private void manager_NewFeedItem(object sender, ItemEventArgs<FeedItem> e) 
    { 
     //Got a new article. Marshall to the UI thread 
     Dispatcher.Invoke(DispatcherPriority.Background, new FeedDelegate(AddItem), e.Item); 
    } 

    private void AddItem(FeedItem itm) 
    { 
     lock (this) 
     { 
      ticker.Items.Enqueue(new TickerItem(itm)); 
      txtItems.Text = ticker.Items.Count.ToString(); 
     } 
    } 

    private void homequicktip_DoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) 
    { 
     //Doubleclicked to homequicktip notification 
     DoubleAnimation fadeouthomequicktip = new DoubleAnimation(); 
     fadeouthomequicktip.From = 1; 
     fadeouthomequicktip.To = 0.0; 
     fadeouthomequicktip.Duration = new Duration(TimeSpan.FromSeconds(1)); 

     //Play fade out animation on homequicktip 
     homequicktip.BeginAnimation(Callout.OpacityProperty, fadeouthomequicktip); 
    } 

    private void MainWindow_Activated(object sender, System.EventArgs e) 
    { 
     //Start feed manager 
     manager.Start(); 

     //Load up clock and play startup animations 
     dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); 
     dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); 
     dispatcherTimer.Interval = new TimeSpan(0,0,1); 
     dispatcherTimer.Start(); 

     //Rotate arcs for nice effect 

     //Arc 1 rotation 
     DoubleAnimation arcrotateAnim1 = new DoubleAnimation(); 
     arcrotateAnim1.From = -70; 
     arcrotateAnim1.To = -3600; 
     arcrotateAnim1.AutoReverse = true; 
     arcrotateAnim1.Duration = new Duration(TimeSpan.FromSeconds(30)); 
     arcrotateAnim1.RepeatBehavior = RepeatBehavior.Forever; 
     arc1.RenderTransformOrigin = new Point(0.5, 0.5); 
     RotateTransform rt = new RotateTransform(); 
     arc1.RenderTransform = rt; 
     rt.BeginAnimation(RotateTransform.AngleProperty, arcrotateAnim1); 

     //Arc 2 rotation 
     DoubleAnimation arcrotateAnim2 = new DoubleAnimation(); 
     arcrotateAnim2.From = 90; 
     arcrotateAnim2.To = 3690; 
     arcrotateAnim2.AutoReverse = true; 
     arcrotateAnim2.Duration = new Duration(TimeSpan.FromSeconds(30)); 
     arcrotateAnim2.RepeatBehavior = RepeatBehavior.Forever; 
     arc1.RenderTransformOrigin = new Point(0.5, 0.5); 
     RotateTransform rt2 = new RotateTransform(); 
     arc2.RenderTransform = rt2; 
     rt2.BeginAnimation(RotateTransform.AngleProperty, arcrotateAnim2); 
    } 
    private void Window_Closing(object sender, CancelEventArgs e) 
    { 
     manager.Stop(); 
     manager.SaveReadFeeds(); 
    } 

    private void Window_SizeChanged(object sender, SizeChangedEventArgs e) 
    { 
     if (e.HeightChanged) 
     { 
      if (e.NewSize.Height != height) Height = height; 
     } 
    } 

    private void btnLock_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     if (WindowStyle == WindowStyle.None) 
     { 
      WindowStyle = WindowStyle.ToolWindow; 
      height = FULL_HEIGHT; 
      Height = height; 
     } 
     else 
     { 
      WindowStyle = WindowStyle.None; 
      height = SHORT_HEIGHT; 
      Height = height; 
     } 
    } 

    private void btnStop_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     btnStop.Visibility = Visibility.Collapsed; 
     btnGo.Visibility = Visibility.Visible; 

     ticker.Stop(); 
    } 

    private void btnGo_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     btnStop.Visibility = Visibility.Visible; 
     btnGo.Visibility = Visibility.Collapsed; 

     ticker.Start(); 
    } 
     private void dispatcherTimer_Tick(object sender, EventArgs e) 
     { 
      //Updating clock 
      timeLabel.Content = DateTime.Now.ToString(); 
      dispatcherTimer.Start(); 
     } 

     private void searchTextbox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
     { 
      if (e.Key == System.Windows.Input.Key.Enter) 
      { 
      //Enter key was pressed - begin search 

      //Create instance of SearchWindow 
      SearchWindow SearchWindow = new SearchWindow(); 

      //Memorize current text in TextBox so it doesn't look like we've changed anything 
      searchInput = searchTextBox.Text; 

      //Pressed enter on searchTextBox 
      if (searchTextBox.Text.Contains(" ")) 
      { 
       //Search input contains spaces which needs to be removed before search can happen 
       searchTextBox.Text.Replace(" ", "+"); 
      } 

      //Open search 
      SearchWindow.searchBrowser.Navigate("http://www.wolframalpha.com/input/?i=" + searchTextBox.Text); 
      SearchWindow.Show(); 
      } 
     } 
} 
} 

TickerItem.xaml:

<UserControl 
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" 
mc:Ignorable="d" 
x:Class="Jarloo.RumorMill4.TickerItem" 
x:Name="UserControl" 
d:DesignWidth="640" d:DesignHeight="480" Height="39"> 

<Grid Height="39" > 
    <TextBlock x:Name="PART_TextBlock" Foreground="#FFFFFFFF" Height="18" VerticalAlignment="Top" TextWrapping="NoWrap"> 
     <Hyperlink x:Name="hlLink" RequestNavigate="hpLink_RequestNavigate"> 
      <TextBlock x:Name="txtTitle" Foreground="#FFFFFFFF" TextWrapping="NoWrap"></TextBlock> 
     </Hyperlink> 
    </TextBlock> 
    <TextBlock x:Name="txtDate" Margin="0,12,0,1" Foreground="#FF939393" TextWrapping="NoWrap" FontSize="10"/> 
    <TextBlock x:Name="txtSource" Margin="0,20,0,1" Foreground="#FFD47432" TextWrapping="NoWrap" FontSize="10" /> 
</Grid> 
</UserControl> 

TickerItem.xaml.cs:

using System; 
using System.Diagnostics; 
using System.Windows.Controls; 
using System.Windows.Navigation; 
using blablablabla.Feed; 

namespace blablablabla 
{ 
public partial class TickerItem 
{ 
    public TickerItem(FeedItem item) 
    { 
     InitializeComponent(); 

     FeedItem = item; 

     txtDate.Text = item.PubDate; 
     txtTitle.Text = item.Title; 

     if (item.Link.ToLower().StartsWith("http")) 
     { 
      try 
      { 
       hlLink.NavigateUri = new Uri(item.Link); 
      } 
      catch 
      { 
      } 
     } 

     txtSource.Text = item.Source; 
    } 

    public FeedItem FeedItem { get; private set;} 

    public string PubDate 
    { 
     get 
     { 
      TextBlock date = (TextBlock)FindName("txtDate"); 
      return date.Text; 
     } 
    } 

    public string Title 
    { 
     get 
     { 
      return txtTitle.Text; 
     } 
    } 

    public string Url 
    { 
     get 
     { 
      return hlLink.NavigateUri.ToString(); 
     } 
    } 

    public string Source 
    { 
     get 
     { 
      return txtSource.Text; 
     } 
    } 

    private void hpLink_RequestNavigate(object sender, RequestNavigateEventArgs e) 
    { 
     Process.Start(new ProcessStartInfo(e.Uri.ToString())); 
    } 
} 
} 

Ticker.cs:

using System; 
using System.Collections.Generic; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Threading; 

namespace blablablabla 
{ 
public class Ticker<T> where T : FrameworkElement 
{ 
    private readonly DispatcherTimer displayTimer = new DispatcherTimer(); 

    public EventHandler<ItemEventArgs<T>> ItemDisplayed; 

    public bool Running { get; set; } 
    public double SeperatorSize { get; set; } 
    public TimeSpan Speed { get; set; } 
    public Queue<T> Items { get; set; } 
    public Panel Container { get; private set; } 

    public void Stop() 
    { 
     displayTimer.Stop(); 
     Running = false; 
    } 

    public void Start() 
    { 
     displayTimer.Start(); 
     displayTimer.Interval = new TimeSpan(0,0,0,1); 
     Running = true; 
    } 

    public Ticker(Panel container) 
    { 
     SeperatorSize = 25; 

     Container = container; 

     Container.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); 
     Container.Arrange(new Rect(Container.DesiredSize)); 

     Speed = new TimeSpan(0, 0, 0, 40); 

     Items = new Queue<T>(); 

     displayTimer.Tick += displayTimer_Tick; 
     displayTimer.Start(); 
     Running = true; 
    } 

    private void displayTimer_Tick(object sender, EventArgs e) 
    { 
     DisplayNextItem(); 
    } 

    private void DisplayNextItem() 
    { 
     if (Items.Count == 0) return; 

     T item = Items.Dequeue(); 

     Container.Children.Add(item); 

     AnimateMove(item); 

     if (ItemDisplayed != null) ItemDisplayed(this, new ItemEventArgs<T>(item)); 
    } 

    private void AnimateMove(FrameworkElement e) 
    { 
     const double to = -500; 

     e.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); 
     e.Arrange(new Rect(e.DesiredSize)); 

     double from = Container.ActualWidth; 

     int unitsPerSec = Convert.ToInt32(Math.Abs(from - to)/Speed.TotalSeconds); 
     int nextFire = Convert.ToInt32((e.ActualWidth + SeperatorSize)/unitsPerSec); 

     displayTimer.Stop(); 
     displayTimer.Interval = new TimeSpan(0, 0, nextFire); 
     displayTimer.Start(); 

     TaggedDoubleAnimation ani = new TaggedDoubleAnimation 
             { 
              From = from, 
              To = to, 
              Duration = new Duration(Speed), 
              TargetElement = e 
             }; 

     ani.Completed += ani_Completed; 

     TranslateTransform trans = new TranslateTransform(); 
     e.RenderTransform = trans; 

     trans.BeginAnimation(TranslateTransform.XProperty, ani, HandoffBehavior.Compose); 
    } 

    private void ani_Completed(object sender, EventArgs e) 
    { 
     Clock clock = (Clock) sender; 
     TaggedDoubleAnimation ani = (TaggedDoubleAnimation) clock.Timeline; 

     FrameworkElement element = ani.TargetElement; 
     Container.Children.Remove(element); 
    } 
} 
} 

Ошибка следующая: она не может быть переведена на 100% должным образом, потому что я норвежец, и ошибка была напечатана на норвежском языке. Обратите внимание:

Ошибка:

Типа blablablabla.TickerItem не может быть использован в качестве параметра типа T в универсальном типе или методе blablablabla.Ticker. Он не существует какой-либо неявной ссылки-конверсии из blablablabla.TickerItem в System.Windows.FrameworkElement

Вы знаете, что это значит?

Я ДЕЙСТВИТЕЛЬНО застрял здесь, пожалуйста, помогите! Благодаря!

+0

на котором вы получаете эту ошибку? – Kenneth

+0

Строка 29, в новом добавленном файле кода, проверьте код сейчас. Эта строка: private readonly Тикер тикер; – user1446632

+0

Не могли бы вы попытаться включить полное пространство имен? Возможно, это смешение ссылок. Обычно это должно работать – Kenneth

ответ

1

У Вас есть ошибка в вашем XAML:

<UserControl 
    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" 
    mc:Ignorable="d" 
    x:Class="Jarloo.RumorMill4.TickerItem" 
    x:Name="UserControl" 
    d:DesignWidth="640" d:DesignHeight="480" Height="39"> 

Атрибут x:Class должен иметь следующее значение:

MySoftware_Inspire.TickerItem 

Вы, наверное, забыли изменить это после того, как после урока

+0

Привет, поэтому приложение запускается, все другие функции являются нормальными. Но в нем нет ни фидов, ни идей? Как вы отправили копию, которую я отправил? – user1446632